python - 如何在一行for循环内的字典中添加另一个属性

标签 python list dictionary

这个问题在这里已经有了答案:





Add an element in each dictionary of a list (list comprehension)

(7 个回答)



Create a dictionary with list comprehension

(14 个回答)


去年关闭。




我有一个字典列表和一个字符串。我想添加一个 selected列表中每个字典中的属性。我想知道这是否可以使用单衬。
这是我的输入:

saved_fields = "apple|cherry|banana".split('|')
fields = [
    {
        'name' : 'cherry'
    }, 
    {
        'name' : 'apple'
    }, 
    {
        'name' : 'orange'
    }
]
这是我的预期输出:
[
    {
        'name' : 'cherry',
        'selected' : True
    }, 
    {
        'name' : 'apple',
        'selected' : True
    }, 
    {
        'name' : 'orange',
        'selected' : False
    }
]
我试过这个:
new_fields = [item [item['selected'] if item['name'] in saved_fields] for item in fields]

最佳答案

我不一定认为“单行方式”是最好的方式。

s = set(saved_fields)  # set lookup is more efficient 
for d in fields:
    d['status'] = d['name'] in s

fields
# [{'name': 'cherry', 'status': True},
#  {'name': 'apple', 'status': True},
#  {'name': 'orange', 'status': False}]
简单的。明确的。明显的。
这会就地更新您的字典,如果您有很多记录或除“名称”和“状态”之外的其他键但您没有告诉我们,这会更好。

如果你坚持单行,这是一个保留其他键:
[{**d, 'status': d['name'] in s} for d in fields]  
# [{'name': 'cherry', 'status': True},
#  {'name': 'apple', 'status': True},
#  {'name': 'orange', 'status': False}]
这是 list comprehension syntax并创建一个新的字典列表,保持原来的不变。
{**d, ...} 部分对于保留未以其他方式修改的 key 是必要的。我没有看到任何其他答案这样做,所以认为值得一提。
扩展解包语法仅适用于python3.5+,对于旧版本,更改{**d, 'status': d['name'] in s}dict(d, **{'status': d['name'] in s}) .

关于python - 如何在一行for循环内的字典中添加另一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62770893/

相关文章:

python - 等待按钮点击

python - 使用 sqlalchemy 和 psycopg2 将数据帧推送到 postgres

python - 链式 celery 任务是否保证在同一节点工作线程上运行?

python - 在python中使用索引创建一个包含列表子集的新列表

list - 合并rhandsontable中的多个单元格

python - 将字符串元组转换为字典

Python 文档字符串搜索 - 类似于 MATLAB `lookup` 或 Linux `apropos`

java - 在某个值之后搜索列表中的最小元素

python - 字典元素之间的欧氏距离

带有 list 关键字的 Python 字典