简体   繁体   English

如何将列表项作为值添加到字典中

[英]How to add the list items to a dictionary as value

I have a Python dictionary as follows:我有一个 Python 字典如下:

{
    "ABC": "32066",
    "XYZ": "4413",
    "CCC": "4413",
    "DDD": "32064",
}

For the key "ABC" I have list ['wood', 'missi'] , if no value is present then we need to assign nulls.对于键"ABC" ,我有列表['wood', 'missi'] ,如果不存在任何值,那么我们需要分配空值。 The expected output as below:预期的 output 如下:

{
    "ABC": ["32066", "wood", "missi"],
    "XYZ": ["4413", null],
    "CCC": ["4413", null],
    "DDD": ["32064", null],
}

Basically you want to edit dictionary values to consist a list of two items.基本上,您想要编辑字典值以包含两个项目的列表。 First item is already the value itself, second one should come from a list.第一项已经是值本身,第二项应该来自列表。 Whenever the list finishes giving item, you want to get None .每当列表完成提供项目时,您都希望获得None You can use itertools.zip_longest :您可以使用itertools.zip_longest

from itertools import zip_longest
from pprint import pprint

d = {
    "ABC": "32066",
    "XYZ": "4413",
    "CCC": "4413",
    "DDD": "32064",
}
lst = ["wood", "missi"]


for (k, v), item in zip_longest(d.items(), lst, fillvalue=None):
    d[k] = [v, item]

pprint(d, sort_dicts=False)

output: output:

{'ABC': ['32066', 'wood'],
 'XYZ': ['4413', 'missi'],
 'CCC': ['4413', None],
 'DDD': ['32064', None]}

Note1: Remember you cannot have two identical keys in dictionary, next one will overwrite the previous one.注意1:记住你不能在字典中有两个相同的键,下一个会覆盖前一个。

Note2: In Python we have None , not null.注 2:在 Python 中我们None ,而不是 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM