基于列表中的键值创建新字典。

huangapple go评论142阅读模式
英文:

Creating new Dictionary based on key values in list

问题

I have dictionary D1 and list l1. I want to create a new dictionary D2 by selecting key-value pairs from the list.

Is there any direct way to do this, or do I need to use a for loop on the 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 the output to be like:

dict2 = {'v1_rev':'30000','v2_rev':'4444','v3_rev':'676373'}

英文:

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'}

答案1

得分: 2

使用字典推导式:

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}
英文:

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}

huangapple
  • 本文由 发表于 2023年3月9日 23:45:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定