Python中2个不同长度列表的字典

时间:2018-03-09 09:24:48

标签: python list dictionary

qeustion是我应该如何用两个不同长度的列表创建一个字典。我没有字典。我想创建字典。

我想在应用split方法时,从两个具有不同长度的列表中创建一个字典。 Forexample

 names
 Out[41]: 
 ['Georgie Porgie',
  'Queen St. Cafe',
  'Dumplings R Us',
  'Mexican Grill',
  'Deep Fried Everything']

  cuisines
  Out[42]: ['Canadian,Pub Food', 'Malaysian,Thai', 'Chinese', 'Mexican', 
  'Pub Food']

  cuisines_splited
  Out[43]: 
  [['Canadian', 'Pub Food'],
  ['Malaysian', 'Thai'],
  ['Chinese'],
  ['Mexican'],
  ['Pub Food']]

我想创建一个字典,使用cuisines_splited作为键和名称作为值。到目前为止,我已经尝试过,但它没有给出正确答案。

cuisine_to_names = {}

for cuis, name in zip(cuisines_splited, names):
    for i in cuis:
        cuisine_to_names[i] = name


cuisine_to_names
Out[46]: 
{'Canadian': 'Georgie Porgie',
 'Chinese': 'Dumplings R Us',
 'Malaysian': 'Queen St. Cafe',
 'Mexican': 'Mexican Grill',
 'Pub Food': 'Deep Fried Everything',
 'Thai': 'Queen St. Cafe'}

所需的输出是:

{'Canadian': ['Georgie Porgie'],
 'Pub Food': ['Georgie Porgie', 'Deep Fried Everything'],
 'Malaysian': ['Queen St. Cafe'],
 'Thai': ['Queen St. Cafe'],
 'Chinese': ['Dumplings R Us'],
 'Mexican': ['Mexican Grill']}

2 个答案:

答案 0 :(得分:4)

您需要有类似的列表才能开始。在压缩和使用defaultdict时需要拆分。

from collections import defaultdict

names = ['Georgie Porgie', 'Queen St. Cafe', 'Dumplings R Us', 'Mexican Grill', 'Deep Fried Everything']
cuisines =  ['Canadian,Pub Food', 'Malaysian,Thai', 'Chinese', 'Mexican',  'Pub Food']

from collections import defaultdict

d = defaultdict(list)
for mk, v in zip(cuisines, names):
    for k in mk.split(','):
        d[k.strip()].append(v.strip())

print(d)

out:
defaultdict(<class 'list'>, {
    "Canadian": ["Georgie Porgie"],
    "Pub Food": ["Georgie Porgie", "Deep Fried Everything"],
    "Malaysian": ["Queen St. Cafe"],
    "Thai": ["Queen St. Cafe"],
    "Chinese": ["Dumplings R Us"],
    "Mexican": ["Mexican Grill"]
})

答案 1 :(得分:1)

您可以使用defaultdict

进行拆分和合并功能
def split(names, cuisines):
    for name, cuisine in zip(names, cuisines):
        for c in cuisine.split(','):
            yield name, c
from collections import defaultdict
def combine(splits):
    result = defaultdict(list)
    for name, cuisine in splits:
        result[cuisine].append(name)
    return(result)
combine(split(names, cuisines))
defaultdict(list,
            {'Canadian': ['Georgie Porgie'],
             'Chinese': ['Dumplings R Us'],
             'Malaysian': ['Queen St. Cafe'],
             'Mexican': ['Mexican Grill'],
             'Pub Food': ['Georgie Porgie', 'Deep Fried Everything'],
             'Thai': ['Queen St. Cafe']})