简体   繁体   English

任何从字典中形成字典的pythonic方法,其中很少有键具有列表值?

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

Example 1:示例 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.由于 key2 中 list 的第一个值为 0,我们不会在这种情况下继续。 Numbers of dictionaries generated should be 7.生成的字典数应为 7。

Example 2:示例 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只会创建 1 个字典

Here's a solution using for loops, where n refers to the length of the lists inside the Items dictionary:这是一个使用 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)

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.请注意,我将 Items dict 中的值更改为列表,而不是列表的字符串表示形式。

暂无
暂无

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

相关问题 从词典列表中选择一些词典关键字,同时还添加新关键字 - Select few Dictionary Keys from list of dictionaries while also adding new keys 根据字典替换列表中值的Pythonic方法 - Pythonic way to replace values in a list according to a dictionary 用字典中的值交换键的最佳方法,其中值在列表中? - Best way to exchange keys with values in a dictionary, where values are in a list? Python将字典中的键具有多个值的字典转换为元组列表 - Python convert dictionary where keys have multiple values into list of tuples Python 3:如何创建一个包含多个字典的字典,其中键也有多个值? - Python 3: How to create a Dictionary with multiple dictionaries in it and where the keys also have multiple values? 从字典中过滤某些键的最快方法,这些字典存储在字典列表中,而字典列表又存储在字典中 - Fastest way to filter for certain keys from dictionaries which are stored in a list of dictionaries which is in turn stored in a dictionary 有没有一种pythonic的方法来替换字典中的nan值? - Is there a pythonic way to replace nan values from dictionary? Pythonic方法将键与单个字典的公共值合并 - Pythonic way to merge keys with common values for a single dictionary 以大多数pythonic方式从词典列表中生成配置样式的文件 - generating config styled file from list of dictionaries in most pythonic way 如何以pythonic方式从嵌套字典中获取键 - How to get keys from nested dictionary in a pythonic way
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM