[英]Is there a way to store values in one dictionary key that has multiple optional values?
[英]store multiple values for one key in dictionary
我有一個數據列表,它有2個值:
a 12
a 11
a 5
a 12
a 11
我想使用字典,所以我最終得到每個鍵的值列表。 第1列可能有不同的條目,如'b'
,因此我可以根據第1列作為鍵排列數據,而第2列是每個鍵的數據
[a:12,11,5]
我該如何實現這一目標? 根據我的閱讀,如果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]
我是否以錯誤的方式處理問題?
Python dicts只能為一個鍵提供一個值,因此您無法以您嘗試的方式分配多個值。
而是將多個值存儲在與鍵對應的列表中,以使列表成為與鍵對應的一個值 :
d = {}
d["a"] = []
d["a"].append(1)
d["a"].append(2)
>>> print d
{'a': [1, 2]}
您可以使用defaultdict
來簡化此操作,如果密鑰不存在,則會初始化密鑰,如下所示:
from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
>>> print d
defaultdict(<type 'list'>, {'a': [1, 2]})
如果您不想為鍵重復值,則可以使用set而不是list。 但要注意一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子句的列表來檢查值
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.