【问题标题】:Match list elements with values of dictionary将列表元素与字典值匹配
【发布时间】:2019-02-24 08:44:25
【问题描述】:

我在列表中有字典:-

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'] 

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

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

【问题讨论】:

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


【解决方案1】:

使用列表推导。

例如:

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'}]

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      【解决方案3】:
      print [dict for dict in L if dict["term"] in words]
      

      【讨论】:

        【解决方案4】:

        问题是您正在打印(k,v),它只是一个字典条目的键和值。如果你想拥有整本字典,你必须把整本字典放在 print 语句中。

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

        【讨论】:

          猜你喜欢
          • 2019-05-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-24
          • 1970-01-01
          • 2018-04-15
          • 1970-01-01
          相关资源
          最近更新 更多