【问题标题】:How to add a key value that's a list only if they have matching values?仅当它们具有匹配值时,如何添加作为列表的键值?
【发布时间】:2019-05-12 18:05:38
【问题描述】:

所以我有这个字典列表:

[{u'id': u'53532', u'name': u'IMG_1.jpg'},
 {u'id': u'53533', u'name': u'IMG_2.jpg'},
 {u'id': u'53534', u'name': u'IMG_3.jpg'}]

还有这个元组列表:

[(53532, image ,'https://sample.jpg'),
 (53533, image ,'https://sample.jpg'),
 (53534, image ,'https://sample.jpg')
]

如何将字典的 id 值与元组中的值匹配,如果它们匹配,则将元组添加到匹配的字典中的新键:

例如,如果它们匹配看起来像这样:

{u'id': u'53532',
 u'name': u'IMG_1.jpg',
 u'img_attr':(53532, image ,'https://sample.jpg')
}

【问题讨论】:

  • OP 提到它是 Python2.7 -> 添加标签

标签: python python-2.7 list dictionary tuples


【解决方案1】:

Python 3.5+

您可以将您的元组列表转换为具有元组值的字典,以 id 为键:

d = {i: tuple(j) for i, *j in L_tup}

然后对结果使用列表推导:

res = [{**myd, 'img_attr': d[int(myd['id'])]} for myd in L_dict]

Python 2.7

Python 2.x 不支持序列和字典解包。在这里你可以使用:

d = {i: (j, k) for i, j, k in L_tup}

for myd in L_dict:
    myd['img_attr'] = d[int(myd['id'])]

那么你想要的结果就是L_dict

【讨论】:

  • 只是让你知道 OP 现在提到他们正在使用 2.7
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2022-02-08
  • 2023-01-10
  • 1970-01-01
相关资源
最近更新 更多