匹配两个列表的键名和值

时间:2019-11-02 16:30:20

标签: python

如何在两个列表中创建名称相似的值的字典?

@Bean
public GeoJsonModule geoJsonModule() {
    return new GeoJsonModule();
}

生成的字典应类似于:

color = ['blue','red','orange',.........]

color_variation = ['blue_0121', 'sea_blue', 'red_0234', 'red_light', 'orange_0120', .........]

我尝试过:

color_dict = {'blue':['blue_0121', 'sea_blue'], 'red': ['red_0234', 'red_light'], 'orange': ['orange_0120'], 'purple': [..........]}

如何匹配要分配给字典的值?

3 个答案:

答案 0 :(得分:2)

您可以进行字典理解:

{c: [v for v in color_variation if c in v] for c in color}

示例

color = ['blue','red','orange']
color_variation = ['blue_0121', 'sea_blue', 'red_0234', 'red_light', 'orange_0120']

print({c: [v for v in color_variation if c in v] for c in color})
# {'blue': ['blue_0121', 'sea_blue'], 'red': ['red_0234', 'red_light'], 'orange': ['orange_0120']}

答案 1 :(得分:0)

您可以在这里defaultdict

使用
from collections import defaultdict

l = defaultdict(list)

for c in color:
     for color_var in color_variation:
         if c in color_var:
             l[c].append(color_var)

l

defaultdict(list,
            {'blue': ['blue_0121', 'sea_blue'],
             'red': ['red_0234', 'red_light'],
             'orange': ['orange_0120']})

答案 2 :(得分:0)

您可以尝试使用itertools.groupby()

import itertools

colors=["red", "blue","green","orange"]
color_variation=["baby-blue","light orange","burgundy red","greenwich green","darkish green", "red567","navy blue","grapefruit red"]
keyfunc=lambda x: next(c for c in colors if c in x)

color_variation=sorted(color_variation, key=keyfunc)
res={k: list(v) for k, v in itertools.groupby(color_variation, keyfunc)}

print(res)

输出:

{'blue': ['baby-blue', 'navy blue'], 'green': ['greenwich green', 'darkish green'], 'orange': ['light orange'], 'red': ['burgundy red', 'red567', 'grapefruit red']}

[Program finished]