我想将值附加到字典中的键,其中值实际上是列表。可以有一个列表,也可以有多个列表。
我目前尝试的方式是,我尝试添加的新列表只会覆盖上一个列表。据我所知,我也不能像这样将列表附加到字典:
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]
]
}
但老实说,在某些时候只是考虑使用类?
关于python - 如何将多个列表附加到 python 字典中的一个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34539065/