Python在字典中复制键。(一对多关系)

问题描述 投票:-2回答:3

我写了一个下面的python脚本来打印python字典中与键相关的所有值。我使用来自我做的rest api调用的值创建了python字典。字典有重复的键。

dict = {'a':'b', 'a':'c', 'b':'d'}.

我经历过邮政Is there a way to preserve duplicate keys in python dictionary

我可以使用下面的脚本获得所需的输出

import collections

data = collections.defaultdict(list)

val=input("Enter a vlaue:")

for k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')):

     data[k].append(v)

#print(list(data.keys()))

if str(val) in list(data.keys()):

    for i in data[val]:

        print(i)

我很惊讶将字典转换为元组元组。例如:{'a':'b', 'a':'c', 'b':'d'}(('a', 'b'), ('a', 'c'), ('b', 'c'))。是否有办法在不更改重复值的情况下执行此操作(我需要重复键)?

python python-3.x dictionary tuples
3个回答
0
投票

你的dict没有重复的密钥,这在没有猴子修补的python中是不可能的

您创建的是包含值{a:[b,c],b:[d]}的列表字典

将这样的dict转换为元组,只需遍历列表即可

data = {"a":["b","c"], "b":["d"]}

def to_tuples(data_dictionary):
    for key, values in data_dictionary.items():
        for value in values:
            yield key, value

print(list(to_tuples(data)))
>>>[('a', 'b'), ('a', 'c'), ('b', 'g')]

0
投票

也许这就是你想要的:

>>> import collections
>>> 
>>> data = collections.defaultdict(list)
>>> 
>>> for k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')):
...     data[k].append(v)
... 
>>> print(dict(data))
{'a': ['b', 'c'], 'b': ['c']}
>>> 
>>> l = []
>>> for k, v in data.items():
...     l.extend((k, v2) for v2 in v)
... 
>>> print(tuple(l))
(('a', 'b'), ('a', 'c'), ('b', 'c'))

希望能帮助到你。 =)


0
投票

字典有唯一的键。这就是我认为你想要的:

data = {'a': ['b', 'c'], 'b': ['c']}

data_tuples = tuple((k, i) for k, v in data.items() for i in v)

# output: (('a', 'b'), ('a', 'c'), ('b', 'c'))
© www.soinside.com 2019 - 2024. All rights reserved.