Skip to content

Instantly share code, notes, and snippets.

@jodyphelan
Last active June 1, 2020 13:50
Show Gist options
  • Select an option

  • Save jodyphelan/db74f7966992894fea2d19611ed2b064 to your computer and use it in GitHub Desktop.

Select an option

Save jodyphelan/db74f7966992894fea2d19611ed2b064 to your computer and use it in GitHub Desktop.
"""
I want to loop through a file that contains:
Rv0001 10
Rv0001 20
Rv0002 50
Rv0003 70
and I want something that looks like this:
{
"Rv0001": [10,20],
"Rv0002": [50],
"Rv0003": [70]
}
"""
# Solution 1
results = {}
for line in open("file.txt"):
row = lines.strip().split()
if row[0] not in results:
results[row[0]] = []
results[row[0]].append(int(row[1]))
# Solution 2 with defaultcdict
results = defaultdict(list)
for line in open("file.txt"):
row = lines.strip().split()
results[row[0]].append(int(row[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment