python如何将dic值与列表项匹配

时间:2017-05-20 19:36:07

标签: python dictionary

countr={'517132': 2017, '1002063365': 116, '226022': 34, '51002': 3, '219006': 117, '222034': 45, '224032': 42, '517195': 103, '731120': 1516
'3254':12,'456':11}

r1=[224032, 517132, 226022, 1002063365, 222034, 219006, 517195, 35015, 731120, 51002]
r={}
for i in r1:
r[i]=countr.get(i)
我试图制作新的词组 我的意思是,如果countr键与r1值匹配

将新的dic r值添加为键,将COUNTR匹配的值添加为值。 但是当我学习这段代码时,结果是无。

'224032':None, '517132'=None....'1002063365':None]

有没有办法将dic值与列表匹配? 这是我想要的输出

r=[517132': 2017, '1002063365': 116, '226022': 34, '51002': 3, '219006': 117, '222034': 45, '224032': 42, '517195': 103, '731120': 1516]

2 个答案:

答案 0 :(得分:0)

如果我做得对,这就是你想要的:

countr={'517132': 2017, '1002063365': 116, '226022': 34, '51002': 3, '219006': 117, '222034': 45 ,'224032': 42, '517195': 103, '731120': 1516,
'3254':12,'456':11}

r1=[224032, 517132, 226022, 1002063365, 222034, 219006, 517195, 35015, 731120, 51002]
r={}
for key in countr:
  if key in str(r1):
    r[key]=countr[key]

print(r)

输出: {'517132': 2017, '1002063365': 116, '226022': 34, '51002': 3, '219006': 117, '222034': 45, '224032': 42, '517195': 103, '731120': 1516}

如果r1是int或sting到很多字典值,你可能还需要重新考虑

答案 1 :(得分:0)

您应该遍历列表元素:

countr = {'517132': 2017, '1002063365': 116, '226022': 34, '51002': 3, '219006': 117,
          '222034': 45, '224032': 42, '517195': 103, '731120': 1516, '3254': 12, '456': 11}

r1 = [224032, 517132, 226022, 1002063365,
      222034, 219006, 517195, 35015, 731120, 51002]

print({k: countr[str(k)] for k in r1 if str(k) in countr})
# {224032: 42, 517132: 2017, 226022: 34, 1002063365: 116, 222034: 45, 219006: 117, 517195: 103, 731120: 1516, 51002: 3}
print({k: countr.get(str(k)) for k in r1})
# {224032: 42, 517132: 2017, 226022: 34, 1002063365: 116, 222034: 45, 219006: 117, 517195: 103, 35015: None, 731120: 1516, 51002: 3}

这种方式更快,更强大。接受的答案将因此示例而失败:

countr={'1': 2017, '2': 116}
r1=[12]