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

时间:2018-01-23 23:16:55

标签: python python-3.x dictionary tuples

我写了一个下面的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'))。是否有办法在不更改重复值的情况下执行此操作(我需要重复键)?

3 个答案:

答案 0 :(得分: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')]

答案 1 :(得分: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'))

希望它有所帮助。 =)

答案 2 :(得分: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'))