Reputation:
I have a list of data, which has 2 values:
a 12
a 11
a 5
a 12
a 11
I would like to use a dictionary, so I can end up with a list of values for each of the key. Column 1 may have a different entry, like 'b'
, so I can arrange data based on column 1 as key, while column 2 is the data for each key
[a:12,11,5]
How do I achieve this? From what I read, if 2 values has the same key, the last one override the previous one, so only one key is in the dictionary.
d={}
for line in results:
templist=line.split(' ')
thekey=templist[0]
thevalue=templist[1]
if thevalue in d:
d[thekey].append(thevalue)
else:
d[thekey]=[thevalue]
Am I approaching the problem using the wrong way?
Upvotes: 5
Views: 12572
Reputation: 77053
Python dicts can have only one value for a key, so you cannot assign multiple values in the fashion you are trying to.
Instead, store the mutiple values in a list corresponding to the key so that the list becomes the one value corresponding to the key:
d = {}
d["a"] = []
d["a"].append(1)
d["a"].append(2)
>>> print d
{'a': [1, 2]}
You can use a defaultdict
to simplify this, which will initialise the key if it doesn't exist with an empty list as below:
from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
>>> print d
defaultdict(<type 'list'>, {'a': [1, 2]})
If you don't want repeat values for a key, you can use a set instead of list. But do note that a set
is unordered.
from collections import defaultdict
d = defaultdict(set)
d["a"].add(1)
d["a"].add(2)
d["a"].add(1)
>>> print d
defaultdict(<type 'set'>, {'a': set([1, 2])})
If you need to maintain order, either use sorted at runtime, or use a list with an if clause to check for values
from collections import defaultdict
d = defaultdict(list)
for item in (1, 2, 1, 2, 3, 4, 1, 2):
if item not in d["a"]:
d["a"].append(item)
>>> print d
defaultdict(<type 'list'>, {'a': [1, 2, 3, 4]})
Upvotes: 10