开发者

python: iterate through list and replace elements with corresponding dictionary values

I am trying to replace list element value with value looked up in dictionary how do I do that?

list = [1, 3, 2, 10]  

d = {'id': 1, 'val': 30},{'id': 2, 'val': 53}, {'id': 3, 'val': 1}, {'id': 4, 'val': 9}, {'id': 5, 'val': 2}, {'id': 6, 'val': 6}, {'id': 7, 'val': 11}, {'id': 8, 'val': 89}, {'id': 9, 开发者_如何学编程'val': 2}, {'id': 10, 'val': 4}

for i in list: 
    for key, v in d.iteritems():
        ???
        ???

so at the end I am expecting:

list = [30, 1, 53, 4]

thank you


D2 = dict((x['id'], x['val']) for x in D)
L2 = [D2[x] for x in L]


   td = (
        {'val': 30, 'id': 1},
        {'val': 53, 'id': 2},
        {'val': 1, 'id': 3},
        {'val': 9, 'id': 4},
        {'val': 2, 'id': 5},
        {'val': 6, 'id': 6},
        {'val': 11, 'id': 7},
        {'val': 89, 'id': 8},
        {'val': 2, 'id': 9},
        {'val': 4, 'id': 10}
        )

    source_list = [1, 3, 2, 10]
    final_list = []

    for item in source_list:
        for d in td:
            if d['id'] == item:
                final_list.append(d['val'])

    print('Source : ', source_list)
    print('Final  : ', final_list)

Result

Source :  [1, 3, 2, 10]
Final  :  [30, 1, 53, 4]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜