![](/img/trans.png)
[英]Select few Dictionary Keys from list of dictionaries while also adding new keys
[英]Any pythonic way to form dictionaries from dictionary where few keys have list values?
示例 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}, ... ]
由於 key2 中 list 的第一個值為 0,我們不會在這種情況下繼續。 生成的字典數應為 7。
示例 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}]
只會創建 1 個字典
這是一個使用 for 循環的解決方案,其中n
指的是 Items 字典中列表的長度:
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)
該代碼輸出以下內容:
[
{'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}
]
請注意,我將 Items dict 中的值更改為列表,而不是列表的字符串表示形式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.