简体   繁体   中英

Any pythonic way to form dictionaries from dictionary where few keys have list values?

Example 1:

Items = {'key1': 1, 'key2': '[0,2,3,4]', 'key3': '[5,6,7,8]', 'key4': 9}
Expected output:

 {'key1':1, 'key2':2,'key3':0, 'key4':9}, {'key1':1, 'key2':0,'key3':5, 'key4':9}, ... ] 

Since first value of list in key2 is 0, We will not proceed in that case. Numbers of dictionaries generated should be 7.

Example 2:

Items = {'key1': 1, 'key2': '[0,2,0,0]', 'key3': '[5,6,7,8]', 'key4': 9}
Expected output:

 [{'key1':1, 'key2':2,'key3':0, 'key4':9}] 

Only 1 dictionary will be create

Here's a solution using for loops, where n refers to the length of the lists inside the Items dictionary:

Items = {'key1': 1, 'key2': [1,2,3,4], 'key3': [5,6,7,8], 'key4': 9}

out = []
n = 4
for i in range(n):
    d = {}
    for k in Items:
        if type(Items[k]) == int:
            d[k] = Items[k]
        elif type(Items[k]) == list:
            d[k] = Items[k][i]
    out.append(d)
print(out)

That code outputs the following:

[
    {'key2': 1, 'key3': 5, 'key1': 1, 'key4': 9},
    {'key2': 2, 'key3': 6, 'key1': 1, 'key4': 9},
    {'key2': 3, 'key3': 7, 'key1': 1, 'key4': 9},
    {'key2': 4, 'key3': 8, 'key1': 1, 'key4': 9}
]

Notice that I changed the values in the Items dict to be lists rather than string representations of lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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