【问题标题】:How to delete matched columns from json dict compare with list in python [closed]如何从json dict中删除匹配的列与python中的列表进行比较[关闭]
【发布时间】:2017-02-14 07:36:16
【问题描述】:

我有一个 json 列表和一个 json dict,我想从 dict 中删除 'id' 列与列表元素匹配的对象。

a = [1,2,3,4,5]
b = {"data":[{"id":1,"name":"shubham"},{"id":8,"name":"rahul"}]

我想要这样的输出:

b = {"data":[{"id":8,"name":"rahul"}]

【问题讨论】:

  • 是的,两者都应该被删除。我的意思是所有与 b 的 id 与列表 a 匹配的元素都应该在 dict 中删除。
  • 那些不是 JSON - JSON 是文本。这些是 Python 中的实际列表和字典。

标签: python json dictionary


【解决方案1】:
a = [1,2,3,4,5]
b = {"data":[{"id":1,"name":"shubham"},{"id":8,"name":"rahul"}]}

s = set(a)
for i, item in enumerate(b['data']):
    if item['id'] in s:
        del b['data'][i]

【讨论】:

    【解决方案2】:
    a = [1,2,3,4,5]
    b = {"data":[{"id":1,"name":"shubham"},{"id":8,"name":"rahul"}]
    
    items = b['data']
    
    for id in a:
       for it in items:
          if it['id'] == id:
             items.remove(it)
    b['data'] = items
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      相关资源
      最近更新 更多