Home > Blockchain >  How to add the list items to a dictionary as value
How to add the list items to a dictionary as value

Time:10-08

I have a Python dictionary as follows:

{
    "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. The expected output as below:

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

CodePudding user response:

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. You can use 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:

{'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.

Note2: In Python we have None, not null.

  • Related