简体   繁体   English

在字典中存储一个键的多个值

[英]store multiple values for one key in dictionary

I have a list of data, which has 2 values: 我有一个数据列表,它有2个值:

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 第1列可能有不同的条目,如'b' ,因此我可以根据第1列作为键排列数据,而第2列是每个键的数据

[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. 根据我的阅读,如果2个值具有相同的键,则最后一个键覆盖前一个键,因此字典中只有一个键。

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? 我是否以错误的方式处理问题?

Python dicts can have only one value for a key, so you cannot assign multiple values in the fashion you are trying to. Python dicts只能为一个键提供一个值,因此您无法以您尝试的方式分配多个值。

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: 您可以使用defaultdict来简化此操作,如果密钥不存在,则会初始化密钥,如下所示:

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. 如果您不想为键重复值,则可以使用set而不是list。 But do note that a set is unordered. 但要注意一set是无序的。

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 如果需要维护顺序,请使用在运行时排序,或使用带有if子句的列表来检查值

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]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM