从lis中的字典创建基于相同密钥对的字典

2024-04-19 02:49:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我的字典列表如下:

 [{'c1': 'Cars ', 'c2': 'Class', 'keywords': 'muv'},
 {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'hatchback'},
 {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'suv'},
 {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'sedan'},
 {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'coupe'},
 {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'electric'},
 {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'diesel'},
 {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'cng'},
 {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'petrol'}]

我想将键keywords的值存储到字典中,以便按键名c1#c2为键c1c2的同一对值。所以预期的输出是这样的:

cars= {'Cars#Class':
['muv','hatchback','suv','sedan','coupe'],
'Cars#FuelType':
['electric','diesel','cng','petrol']}

所以当我使用cars['Cars#Class']的时候,给了我['muv','hatchback','suv','sedan','coupe']。你知道吗


Tags: 字典carsclassc2c1keywordselectricdiesel
3条回答

你可以用itertools.goupby公司做这个。你知道吗

import itertools

l = [{'c1': 'Cars ', 'c2': 'Class', 'keywords': 'muv'},
 {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'hatchback'},
 {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'suv'},
 {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'sedan'},
 {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'coupe'},
 {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'electric'},
 {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'diesel'},
 {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'cng'},
 {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'petrol'}]


result = {}
for key, group in itertools.groupby(l, lambda x: "{}#{}".format(x['c1'].strip(), x['c2'].strip())):
    result[key] = map(lambda x: x['keywords'], list(group))

print(result)

默认dict

您可以在迭代中使用collections.defaultdict。给定词典的输入列表L

from collections import defaultdict

d = defaultdict(list)

for i in L:
    d[i['c1'].strip()+'#'+i['c2']].append(i['keywords'])

结果:

print(d)

defaultdict(list,
            {'Cars#Class': ['muv', 'hatchback', 'suv', 'sedan', 'coupe'],
             'Cars#FuelType': ['electric', 'diesel', 'cng', 'petrol']})

熊猫

如果您愿意使用第三方库,您可以使用Pandas。pd.DataFrame构造函数直接接受字典列表。给定一个输入列表L

import pandas as pd

df = pd.DataFrame(L)

d = df.groupby(df['c1'].str.strip()+'#'+df['c2'])['keywords']\
      .apply(list).to_dict()

print(d)

{'Cars#Class': ['muv', 'hatchback', 'suv', 'sedan', 'coupe'],
 'Cars#FuelType': ['electric', 'diesel', 'cng', 'petrol']}

相关问题 更多 >