Creating new Dictionary based on key values in list

Question:

I have dictionary D1 and list l1 .I want to create new dictionary D2 picking key values from List .
Is there any direct way of doing this or I need to apply through for loop on list .


def main():
   dict ={'acct_number':'10202','acct_name':'abc','v1_rev':'30000','v2_rev':'4444',
          'v3_rev':'676373'}
   vendors_revenue_list =['v1_rev','v2_rev','v3_rev']
   



if __name__ == '__main__':
   main()

I want output like

dict2 = {‘v1_rev’:’30000′,’v2_rev’:’4444′,’v3_rev’:’676373′}

Asked By: pbh

||

Answers:

Use a dict comprehension:

d = {'acct_number':'10202','acct_name':'abc','v1_rev':'30000','v2_rev':'4444',
      'v3_rev':'676373'}
vendors_revenue_list = ['v1_rev','v2_rev','v3_rev']
res = {k : d[k] for k in vendors_revenue_list}
Answered By: Unmitigated
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.