python - 如何将多个列表附加到 python 字典中的一个键?

标签 python list python-2.7 dictionary python-2.x

我想将值附加到字典中的键,其中值实际上是列表。可以有一个列表,也可以有多个列表。

我目前尝试的方式是,我尝试添加的新列表只会覆盖上一个列表。据我所知,我也不能像这样将列表附加到字典:

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/

相关文章:

python - Python 2 和 Python 3 中 exec 函数的行为

scala - 通过python脚本在命令行中执行sbt并输出到文件

python - Kivy kv 文件不工作

java - 用另一个替换列表中的元素

Python Tkinter Canvas 无法绑定(bind)键盘

python - 给定另一个索引号列表,将数字插入列表中

python从多个列表中选择具有引用的最低字母数字值

python-2.7 - DHT 11 温度传感器的 Python GPIO 代码在 PI 2 中失败

python - 重构以消除递归函数中的全局变量

python - Eventlet 或 gevent 或 Stackless + Twisted、Pylons、Django 和 SQL Alchemy