如何迭代字典中所有可能的值?

2024-09-30 12:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python字典,其中每个条目的值要么是一个列表,要么是另一个条目也是列表的字典。我想创建一个python迭代器,它遍历字典中所有可能的状态,其中每个键处的列表定义了该键的可能值。你知道吗

我尝试遍历每个键,并在列表中找到下一个元素作为值,但这只涵盖了一些组合。这是因为一旦一个列表耗尽,您需要重置为第一个值并移动到下一个列表。你知道吗

如果我们把这句话交给迭代器。。。你知道吗

{
    "key0": {
        "key1": [1, 2],
        "key2": [8, 9, 10]
    }
    "key3": [22, 23, 24]
}

它应该产生的第一个迭代是。。。你知道吗

{
    "key0": {
        "key1": 1,
        "key2": 8
    }
    "key3": 22
}

第二个是。。。你知道吗

{
    "key0": {
        "key1": 2,
        "key2": 8
    }
    "key3": 22
}

第三个是。。。 (注意key1是如何返回到1的)

{
    "key0": {
        "key1": 1,
        "key2": 9
    }
    "key3": 22
}

预期结果是迭代字典的每个可能状态(总共18个),其中每个键处的列表定义该键的可能值。你知道吗


Tags: 目的元素列表字典定义状态条目重置
3条回答

以下是我的解决方案:

xdict = {
    "key0": {
        "key1": [1, 2],
        "key2": [8, 9, 10]
    },
    "key3": [22, 23, 24]
}

def iterate (key, index):
    if (type(key) == list):
        if (index >= len(key)):
            return (key[0])
        else:
            return (key[index])
    elif (type(key) == dict):
        result = {}
        for item in key:
            result[item] = iterate(key[item], index)
        return result

在执行了以下测试之后,我得到了您所说的结果

>>> iterate(xdict, 0)
{'key0': {'key1': 1, 'key2': 8}, 'key3': 22}
>>> iterate(xdict, 1)
{'key0': {'key1': 2, 'key2': 9}, 'key3': 23}
>>> iterate(xdict, 2)
{'key0': {'key1': 1, 'key2': 10}, 'key3': 24}

以下是使用itertools.product和递归的简明方法:

from itertools import product

def traverse(d):
    K,V = zip(*d.items())
    for v in product(*(v if isinstance(v,list) else traverse(v) for v in V)):
        yield dict(zip(K,v))

运行示例:

>>> d = {
>>>     "key0": {
>>>         "key1": [1, 2],
>>>         "key2": [8, 9, 10]
>>>     },
>>>     "key3": [22, 23, 24]
>>> }

>>> from pprint import pprint
>>> pprint([*traverse(d)])
[{'key0': {'key1': 1, 'key2': 8}, 'key3': 22},
 {'key0': {'key1': 1, 'key2': 8}, 'key3': 23},
 {'key0': {'key1': 1, 'key2': 8}, 'key3': 24},
 {'key0': {'key1': 1, 'key2': 9}, 'key3': 22},
 {'key0': {'key1': 1, 'key2': 9}, 'key3': 23},
 {'key0': {'key1': 1, 'key2': 9}, 'key3': 24},
 {'key0': {'key1': 1, 'key2': 10}, 'key3': 22},
 {'key0': {'key1': 1, 'key2': 10}, 'key3': 23},
 {'key0': {'key1': 1, 'key2': 10}, 'key3': 24},
 {'key0': {'key1': 2, 'key2': 8}, 'key3': 22},
 {'key0': {'key1': 2, 'key2': 8}, 'key3': 23},
 {'key0': {'key1': 2, 'key2': 8}, 'key3': 24},
 {'key0': {'key1': 2, 'key2': 9}, 'key3': 22},
 {'key0': {'key1': 2, 'key2': 9}, 'key3': 23},
 {'key0': {'key1': 2, 'key2': 9}, 'key3': 24},
 {'key0': {'key1': 2, 'key2': 10}, 'key3': 22},
 {'key0': {'key1': 2, 'key2': 10}, 'key3': 23},
 {'key0': {'key1': 2, 'key2': 10}, 'key3': 24}]

字典不是有序结构,您不应该尝试对其进行迭代。但是,如果必须这样做,方法可以是:

my_dict = {"a":1 ,"b":2,"c":3}

for key in my_dict.keys():
    #print the key
    print(key)
    #print the value corresponding to the key
    print(my_dict[key])

用你想要的任何功能替换指纹,你应该没事!如果您有嵌套的字典或列表,请记住这些值就是(在您的示例中)字典或列表,从那里,您可以以类似的方式在循环中操纵它们。你知道吗

my_dict = {"a":{"a_1":1,"a_2":2} ,"b":{"b_1":1,"b_2":2},"c":{"b_1":1,"b_2":2}}

for key in my_dict.keys():
    #print the key
    print(key)
    #print the dictionary corresponding to the key
    print(my_dict[key])
    for new_key in my_dict[key].keys():
        #print the keys of the nested dictionaries
        print(new_key)
        #print the values of the nested dictionaries
        print(my_dict[key][new_key])

这应该管用

相关问题 更多 >

    热门问题