Filter dict to contain only certain keys?

后端 未结 15 939
耶瑟儿~
耶瑟儿~ 2020-11-22 10:52

I\'ve got a dict that has a whole bunch of entries. I\'m only interested in a select few of them. Is there an easy way to prune all the other ones out?

15条回答
  •  感情败类
    2020-11-22 11:45

    Based on the accepted answer by delnan.

    What if one of your wanted keys aren't in the old_dict? The delnan solution will throw a KeyError exception that you can catch. If that's not what you need maybe you want to:

    1. only include keys that excists both in the old_dict and your set of wanted_keys.

      old_dict = {'name':"Foobar", 'baz':42}
      wanted_keys = ['name', 'age']
      new_dict = {k: old_dict[k] for k in set(wanted_keys) & set(old_dict.keys())}
      
      >>> new_dict
      {'name': 'Foobar'}
      
    2. have a default value for keys that's not set in old_dict.

      default = None
      new_dict = {k: old_dict[k] if k in old_dict else default for k in wanted_keys}
      
      >>> new_dict
      {'age': None, 'name': 'Foobar'}
      

提交回复
热议问题