Python:具有多个值的键的字典。如何将字典打印为分隔值列表的字典集

时间:2017-06-21 08:21:51

标签: python dictionary

我有一个包含多个值的字典,如下所示:

my_dict = {'key0': (0, 1), 'key1': (a, b), 'key2': (x, y)}

我想打印我的字典

my_dict = {'key0': 0, 'key1': a, 'key2': x}, {'key0': 1, 'key1': b, 'key2': y}

我怎样才能做到这一点?请帮忙......

5 个答案:

答案 0 :(得分:3)

如果所有元组的长度相同(即2),您可以使用列表理解:

[{key: value[i] for key, value in my_dict} for i in range(2)]

以下是一个例子:

my_dict = {'key0': (0, 1), 'key1': (1, 2), 'key2': ('a', 'b')}
[{key: value[i] for key, value in my_dict.iteritems()} for i in range(2)]

输出:

[{'key0': 0, 'key1': 1, 'key2': 'a'}, {'key0': 1, 'key1': 2, 'key2': 'b'}]

答案 1 :(得分:0)

没有像a = {}, {}这样的数据结构。但是,您可以将初始字典拆分为2个字符串:

my_dict = {'key0': (0, 1), 'key1': ('a', 'b'), 'key2': ('x', 'y')}
my_dict_1 = dict((key, value[0]) for key, value in my_dict.iteritems())
my_dict_2 = dict((key, value[1]) for key, value in my_dict.iteritems())

结果:

print my_dict_1
{'key0': 0, 'key1': 'a', 'key2': 'x'}
print my_dict_1
{'key0': 1, 'key1': 'b', 'key2': 'y'}

答案 2 :(得分:0)

假设您的所有值都是元组/列表但可能具有不同的大小,您可以执行以下操作:

def expand_dict(input_dict):
    max_size = max(len(v) for v in input_dict.values())
    output_list = [dict() for _ in range(max_size)]
    for k, v in input_dict.items():
        for i, x in enumerate(v):
            output_list[i][k] = x
    return output_list

my_dict = {'key0': (0, 1), 'key1': ('a', 'b'), 'key2': ('x', 'y', 'z')}

print expand_dict(my_dict)

打印:

[{'key2': 'x', 'key1': 'a', 'key0': 0}, {'key2': 'y', 'key1': 'b', 'key0': 1}, {'key2': 'z'}]

答案 3 :(得分:0)

你可以尝试这样:

DoubleBetweenZeroAndTen

从处理时间的角度来看,这是非常有效的,并且还涵盖了所有可能的dict长度情况(如果其中一个元组有3个值不是2,那该怎么办。)

答案 4 :(得分:0)

带有复杂示例的扩展解决方案:

使用过的功能:zip()itertools.zip_longest()

import itertools

my_dict = {'key0': (0, 1), 'key1': ('a', 'b'), 'key2': ('x', 'y'), 'key3': ('z', 'v')}
result = [dict(t) for t in itertools.zip_longest(*[list(zip([k,k],v)) for k,v in my_dict.items()])]

print(result)

输出:

[{'key2': 'x', 'key0': 0, 'key1': 'a', 'key3': 'z'}, {'key2': 'y', 'key0': 1, 'key1': 'b', 'key3': 'v'}]