将列表的 python 字典转换为元组

Convert python dict of lists to a tuple

我想从这里开始:

my_dict = {'key1': ['cat', 'dog'], 'key2': ['horse']}

对此:

my_tuple = [('key1', 'cat'), ('key1', 'dog'), ('key2', 'horse')]

这可能吗?

您可以使用 list comprehension:

[(key, value) for key, lst in my_dict.items() for value in lst]

输出:

[('key1', 'cat'), ('key1', 'dog'), ('key2', 'horse')]

您可以使用以下迭代来实现输出:

my_dict = {'key1': ['cat', 'dog'], 'key2': ['horse']}
my_tuple = []
for val in my_dict:
    for key in my_dict[val]:
        tup = (val, key)
        my_tuple.append(tup)
print(my_tuple)

您将得到以下输出:

[('key1', 'cat'), ('key1', 'dog'), ('key2', 'horse')]