我有两个清单:
alist = ['key1','key2','key3','key3','key4','key4','key5'] blist= [30001,30002,30003,30003,30004,30004,30005]我想合并这些列表并将它们添加到字典中。
我尝试dict(zip(alist,blist))但这给出了:
{'key3':30003,'key2':30002,'key1':30001,'key5':30005,'key4':30004}
所需的字典形式是:
{'key1':30001,'key2':30002,'key3':30003,'key3':30003,'key4':30004,'key4':30004,'key5':30005}
我想保留字典中的重复项以及不在同一个键中加入值(... key3':30003,'key3':30003,...)。这可能吗?
提前致谢。
I have two lists:
alist = ['key1','key2','key3','key3','key4','key4','key5'] blist= [30001,30002,30003,30003,30004,30004,30005]I want to merge these lists and add them to a dictionary.
I try dict(zip(alist,blist)) but this gives:
{'key3': 30003, 'key2': 30002, 'key1': 30001, 'key5': 30005, 'key4': 30004}
The desired form of the dictionary is:
{'key1': 30001, 'key2': 30002, 'key3': 30003,'key3':30003, 'key4': 30004, 'key4': 30004, 'key5': 30005}
I want to keep the duplicates in the dictionary as well as not join the values in the same key (... key3': 30003,'key3':30003,... ).Is it possible?
Thanks in advance.
最满意答案
您不能这样做,因为dict对象具有唯一键。 你应该只使用元组的使用列表:
>>> alist = ['key1','key2','key3','key3','key4','key4','key5'] >>> blist= [30001,30002,30003,30003,30004,30004,30005] >>> zip(alist, blist) [('key1', 30001), ('key2', 30002), ('key3', 30003), ('key3', 30003), ('key4', 30004), ('key4', 30004), ('key5', 30005)]如果要根据键访问所有值,可以使用collections.defaultdict :
>>> from collections import defaultdict >>> my_dict = defaultdict(list) >>> for k, v in zip(alist, blist): ... my_dict[k].append(v) ... >>> my_dict defaultdict(<type 'list'>, {'key3': [30003, 30003], 'key2': [30002], 'key1': [30001], 'key5': [30005], 'key4': [30004, 30004]})您可以访问类似于普通dict对象的defaultdict 。 例如:
>>> my_dict['key3'] [30003, 30003]You can not do that as dict objects have unique keys. You should just the use list of tuple:
>>> alist = ['key1','key2','key3','key3','key4','key4','key5'] >>> blist= [30001,30002,30003,30003,30004,30004,30005] >>> zip(alist, blist) [('key1', 30001), ('key2', 30002), ('key3', 30003), ('key3', 30003), ('key4', 30004), ('key4', 30004), ('key5', 30005)]If you want to access all the values based on the key, you may use collections.defaultdict as:
>>> from collections import defaultdict >>> my_dict = defaultdict(list) >>> for k, v in zip(alist, blist): ... my_dict[k].append(v) ... >>> my_dict defaultdict(<type 'list'>, {'key3': [30003, 30003], 'key2': [30002], 'key1': [30001], 'key5': [30005], 'key4': [30004, 30004]})You can access defaultdict similar to normal dict objects. For example:
>>> my_dict['key3'] [30003, 30003]更多推荐
发布评论