简体   繁体   English

将dict从键/值对扩展到Python中的键/值对

[英]Extend dict from key/values pair to key/value pair in Python

myDict = {'121': ['adrian', 'alex', 'peter'], '122': ['john', 'vic', 'bill']}

I want to 'extend' my dictionary so that each key/value pair consists of one value, instead of a list. 我想“扩展”我的字典,以便每个键/值对都包含一个值,而不是列表。 Tried iterating with myDict.keys() and myDict.values() and construct a new dict, didnt work out (i'm quite new to python3). 尝试使用myDict.keys()和myDict.values()进行迭代,并构造新的字典,但没有解决(我对python3还是很陌生)。 This is what I want to achieve: 这是我要实现的目标:

myNewDict = {'121': 'adrian', '121': 'alex', '121': 'peter', '122': 'john', '122': 'vic', '122':'bill'}

If you don't care about collisions being clobbered, here's a 1-line solution (plus import): 如果您不关心碰撞被破坏,这里是一线解决方案(加上导入):

import functools                                                                   
myDict = {'121': ['adrian', 'alex', 'peter'], '122': ['john', 'vic', 'bill']}   

print(functools.reduce( lambda x,y: dict(x, **y), (dict(map(lambda x: (x,i), myDict[i])) for i in myDict)))

To break apart what this is doing: 打破这是做什么的:

# This is a generator that creates a new dictionary out of each key/valuelist

(dict(map(lambda val: (val,key), myDict[key])) for key in myDict)

# => {'adrian': '121', 'alex': '121': 'peter': '121'}
# => {'john': '122', 'bill': '122', 'vic': '122'}

Once you have that,then call 一旦有了,那就打电话

functools.reduce( lambda x,y: dict(x, **y), <generator here>)

Reduce takes a function and applies it 减少功能并应用

cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. 从左到右累积到序列项,以便将序列减少为单个值。

dict(mydict, **yourdict) combines dictionaries by way of argument unpacking . dict(mydict, **yourdict)通过参数解包的方式组合字典。

Which means that this takes the first dictionary from the list, and combines it with the next dictionary in the list, and so-on and so-forth until all the dictionaries in the list have been combined into one grand dictionary. 这意味着它将从列表中选取第一个词典,然后将其与列表中的下一个词典进行合并,如此反复进行直到列表中的所有词典都合并为一个完整的词典为止。


All that being said, I'd probably do something like this instead: 话虽这么说,我可能会做这样的事情:

inverted = dict((name, k) for k, v in myDict.items() for name in v) 

Alternate syntax using a dictionary comprehension: 使用字典理解的替代语法:

inverted = {name: k for k, v in myDict.items() for name in v}

Based on comments above, here's how to invert the dict and allow multiple values for each key: 根据上面的评论,这是如何反转字典并为每个键允许多个值的方法:

from collections import defaultdict
myNewDict = defaultdict(list)
for staff_id, names in myDict.items():
    for name in names:
        myNewDict[name].append(staff_id)

You might use a defaultdict of set and add instead of list and append if order doesn't matter: 如果顺序无关紧要,则可以使用setadd而不是listappenddefaultdict

from collections import defaultdict
myNewDict = defaultdict(set)
for staff_id, names in myDict.items():
    for name in names:
        myNewDict[name].add(staff_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM