[英]How do I append multiple lists to one key in a python dictionary?
我想將值附加到字典中的鍵,其中值實際上是列表。 可能有一個列表,或者可能有多個列表。
我正在嘗試這樣做的當前方式,我嘗試添加的新列表只是覆蓋了最后一個列表。 據我所知,我不能將列表附加到這樣的字典:
my_dict.append(my_list))
當前代碼互相覆蓋:
urls[domain] = [uri, datecreated]
這可能嗎? 如果是這樣,怎么樣?
示例結果如下所示
print all keys and values in urls{}:
google.com : ['/helloworld', 2010-04-02], ['/apage/anotherpage', 2015-09-12]
microsoft.com : ['/awebpage', 2009-02-01], ['/bananas', 2015-12-24], ['/anothergreaturi', 205-12-10]
您可以將每個詞典條目都列為一個列表,以便附加到該列表。
>>> a = Linter("ahahah")
>>> a.write_file()
>>> a = dict()
>>> a["first"] = []
>>> a["first"].append([1,2,3])
>>> a["first"].append([4,5,6])
>>> a["second"] = []
>>> a["second"].append([7,8,9])
>>> a
{
'second':[
[7, 8, 9]
],
'first': [
[1, 2, 3],
[4, 5, 6]
]
}
但老實說,在某些時候只考慮使用類?
這是你想要實現的目標嗎?
>>> d={'a': ['b']}
>>> d['a']
['b']
>>> d['a'] += ['c']
>>> d['a']
['b', 'c']
您可以使用defaultdict來完成您的需要。
from collections import defaultdict
my_dict = defaultdict(list)
my_dict[1].append([1,2])
my_dict[1].append([3,4])
my_dict[2].append([8,9])
現在,您可以訪問每個鍵元素,就像訪問dictionary
>>> my_dict[1]
[[1, 2], [3, 4]]
>>> for k, v in my_dict.iteritems():
print k,v
1 [[1, 2], [3, 4]]
2 [[8, 9]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.