将列表元素与字典值匹配

时间:2018-09-20 05:43:26

标签: python arrays python-3.x dictionary key

我的字典在列表中为:-

L= [{'id': 3, 'term': 'bugatti', 'bucket_id': 'ad_3'},
     {'id': 4, 'term': 'mercedez', 'bucket_id': 'ad_4'},
     {'id': 8, 'term': 'entertainment', 'bucket_id': 'ad_8'},
     {'id': 8, 'term': 'entertainment', 'bucket_id': 'ad_8'},
     {'id': 9, 'term': 'music', 'bucket_id': 'ad_9'}]

,另一个列表为:-

words=['bugatti', 'entertainment', 'music','politics'] 

所有我想用键words映射列表term的元素,并想要获得相应的字典。预期输出为:

new_list= [{'id': 3, 'term': 'bugatti', 'bucket_id': 'ad_3'},
           {'id': 8, 'term': 'entertainment', 'bucket_id': 'ad_8'},
           {'id': 8, 'term': 'entertainment', 'bucket_id': 'ad_8'},
           {'id': 9, 'term': 'music', 'bucket_id': 'ad_9'}]

我尝试过的方式:

for d in L:
    for k,v in d.items():
        for w in words:
            if v==w:
                print (k,v)

只给我

term bugatti
term entertainment
term entertainemnt
term music

4 个答案:

答案 0 :(得分:2)

使用列表理解。

例如:

L= [{'id': 3, 'term': 'bugatti', 'bucket_id': 'ad_3'},
     {'id': 4, 'term': 'mercedez', 'bucket_id': 'ad_4'},
     {'id': 8, 'term': 'entertainment', 'bucket_id': 'ad_8'},
     {'id': 8, 'term': 'entertainment', 'bucket_id': 'ad_8'},
     {'id': 9, 'term': 'music', 'bucket_id': 'ad_9'}]


words=['bugatti', 'entertainment', 'music','politics']

print([i for i in L if i["term"] in words])

输出:

[{'bucket_id': 'ad_3', 'id': 3, 'term': 'bugatti'},
 {'bucket_id': 'ad_8', 'id': 8, 'term': 'entertainment'},
 {'bucket_id': 'ad_8', 'id': 8, 'term': 'entertainment'},
 {'bucket_id': 'ad_9', 'id': 9, 'term': 'music'}]

答案 1 :(得分:0)

您可以使用列表理解功能,但是我包含了完整的循环,因此您可以更清楚地看到逻辑

new_l = [i for i in l if i['term'] in words]

完整循环

new_l = []
for i in l:
    if i['term'] in words:
        new_l.append(i)

答案 2 :(得分:0)

LocalDate

答案 3 :(得分:-1)

问题是您正在打印(k,v),它只是一个字典条目的键和值。如果要拥有整个词典,则必须将整个词典放入打印语句中。

for d in L:
    for k,v in d.items():
        for w in words:
            if v==w:
                print (d)
相关问题