Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个简单的字典{'a': 1, 'b': 2, 'c': 3, 'd': 4 }和键列表:['a', 'd'].
{'a': 1, 'b': 2, 'c': 3, 'd': 4 }
['a', 'd']
构造仅包含列表中的键的 dict 对象的更好方法是:{'a': 1, 'd': 4}?
{'a': 1, 'd': 4}
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4 } l = ['a', 'd'] new_d = {k:d[k] for k in l}
new_d就是现在{'a': 1, 'd': 4}
new_d
d = {'a':1, 'b':2, 'c':3, 'd':4} c = ['a', 'b'] new_d = {} for key in c: new_d[key]= d[key]