简体   繁体   English

将两个列表合并到一个字典中,以唯一值作为键

[英]Combine two lists in one dictionary that takes unique values as keys

I have this two lists, with same len:我有这两个列表,具有相同的 len:

owner=["John","John","Mark","Bill","John","Mark"]
restaurant_number=[0,2,3,6,9,10]

I want to turn that into a dict that informs the restaurant_number of each owner:我想把它变成一个通知每个所有者的 restaurant_number 的字典:

d={"John":[0,2,9],"Mark":[3,10],"Bill":[6]}

I could do it the ugly way:我可以用丑陋的方式做到这一点:

unique=set(owner)
dict={}
for i in unique:
    restaurants=[]
    for k in range(len(owner)):
        if owner[k] == i:restaurants.append(restaurant_number[k])
    dict[i]=restaurants

Is there a more pythonic way to do that?有没有更蟒蛇的方式来做到这一点?

Something like defaultdict + zip could work here:defaultdict + zip这样的东西可以在这里工作:

from collections import defaultdict

d = defaultdict(list)

owner = ["John", "John", "Mark", "Bill", "John", "Mark"]
restaurant_number = [0, 2, 3, 6, 9, 10]

for o, n in zip(owner, restaurant_number):
    d[o].append(n)

print(dict(d))
{'John': [0, 2, 9], 'Mark': [3, 10], 'Bill': [6]}

Without dependencies.没有依赖。

Given your input:鉴于您的输入:

owner=["John","John","Mark","Bill","John","Mark"]
restaurant_number=[0,2,3,6,9,10]

Prepare the recipient dictionary res having empty list as values, then populate it without the need to zip:准备具有空列表作为值的收件人字典res ,然后在不需要 zip 的情况下填充它:

res = {own: [] for own in set(owner)}

for i, own in enumerate(owner):
  res[own].append(restaurant_number[i])

To get the result得到结果

print(res)
#=> {'Mark': [3, 10], 'Bill': [6], 'John': [0, 2, 9]}

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

相关问题 如何将两个列表组合成键和值并添加到字典? - How to Combine Two Lists into Keys and Values and Add to Dictionary? 如何将两个列表组合到字典中,并将值手动分配给键 - How to combine two lists into a dictionary with the values to the keys assigned manually 将两个列表与一个带有键和值的dict组合并转换为数据帧 - combine two lists to one dict with keys and values and transform into dataframe 如何组合 3 个列表来创建一个具有一个键和两个值的字典? - How to combine 3 lists to create a dictionary with one key and two values? 把字典变成两个列表,一个用于键,另一个用于值? - Turn a dictionary into two lists, one for keys and the other for values? Python:One-Liner 从非唯一键和值列表创建列表字典 - Python: One-Liner to create a dictionary of lists from a list of non-unique keys and values 当值是列表且项目不是唯一时,交换字典键和值 - Swap dictionary keys and values, when values are lists and items are not unique 如何将 2 个列表组合成一个字典,其中键可以有多个值? - How to combine 2 lists into a dictionary, where keys can have multiple values? 如何从具有唯一键和值作为列表的字典中制作 dataframe? - How to make a dataframe from a dictionary with unique keys and values as lists? 字典中的唯一列表值 - Unique lists values in dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM