我有一本看起来像这样的字典
old_dict = {"language":"english","gender":"female","job":"ceo"}
我感兴趣的唯一关键是 "语言""工作""爱好"
使用此逻辑过滤仅适用于原始字典中存在的键。
dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys if your_key in your_keys }
如果不存在为密钥设置null / none值的密钥,我如何更改此代码以添加条件。
your_keys = ["language","job"]
我正在寻找的输出是
{"language":"english","job":"ceo","hobby":None}
答案 0 :(得分:3)
{ key:old_dict.get(key,None) for key in ["language","job", "hobby"]}
输出:
{'hobby': None, 'job': 'ceo', 'language': 'english'}