python - 将相同的键值附加到字典列表中

标签 python python-3.x list dictionary vectorization

我有一个字典列表,我想将相同的键值附加到所有字典。 例如:

l = [
    {'name' : 'abc', 'age' : '20', 'city' : 'abc'},
    {'name' : 'def', 'age' : '20', 'city' : 'def'},
    {'name' : 'hij', 'age' : '20', 'city' : 'hij'},
    {'name' : 'klm', 'age' : '20', 'city' : 'klm'},
    {'name' : 'nop', 'age' : '20', 'city' : 'nop'}
    ]

for d in l:
    d['date'] = '30/10/2019'

输出:

{'name': 'abc', 'age': '20', 'city': 'abc', 'date': '30/10/2019'}
{'name': 'def', 'age': '20', 'city': 'def', 'date': '30/10/2019'}
{'name': 'hij', 'age': '20', 'city': 'hij', 'date': '30/10/2019'}
{'name': 'klm', 'age': '20', 'city': 'klm', 'date': '30/10/2019'}
{'name': 'nop', 'age': '20', 'city': 'nop', 'date': '30/10/2019'}

所以这是可行的,但在我的实际情况中,我有更多的值(2000 个字典,40 个键)。我想知道是否有一种方法可以将日期附加到每个字典而不需要 for。

最佳答案

我只会使用 for 循环。

但是,本着实际回答所提出问题的精神,您可以使用map()以 C 速度运行隐式 for 循环:

>>> from itertools import repeat
>>> from collections import deque
>>> from operator import setitem

>>> _ = deque(map(setitem, l, repeat('date'), repeat('30/10/2019')), maxlen=0)

>>> from pprint import pprint
>>> pprint(l)
[{'age': '20', 'city': 'abc', 'date': '30/10/2019', 'name': 'abc'},
 {'age': '20', 'city': 'def', 'date': '30/10/2019', 'name': 'def'},
 {'age': '20', 'city': 'hij', 'date': '30/10/2019', 'name': 'hij'},
 {'age': '20', 'city': 'klm', 'date': '30/10/2019', 'name': 'klm'},
 {'age': '20', 'city': 'nop', 'date': '30/10/2019', 'name': 'nop

关于python - 将相同的键值附加到字典列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58628620/

相关文章:

python - 如何正确部署需要服务器回调的 Bokeh 应用程序?

python-3.x - Colab 中的 Python 脚本不断抛出错误消息 : IndentationError: unindent does not match any outer indentation level

python - 无法使分屏滚动到底部

java - 比较两个列表时发生奇怪的情况(groovy)

python - list-comprehension "create list"和 "append elements"与简单循环有何不同?

python - 如何修复 "Could not install packages due to an EnvironmentError: HTTPSConnectionPool"错误?

python - 如何将 Opencv 集成到 Tkinter 窗口中

python - 在 Django 中确定和实现趋势算法

python - .format代码只显示第一个字母

c# - 如何按类型排序列表?