英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论