简体   繁体   中英

Use variable storing key from dict1 as new key for dict2

I want to pull keys and their values from a dictionary that meet conditions, then store them in another dictionary. What I thought of so far was:

dict = {'a': 1, 'b': 2}
new_dict = {}
for x in dict:
    new_dict.update(x=dict[x])
print (dict)
print (new_dict)

Here, x stores a key 'a' with value 1 , but when I update new_dict , it stores x: 2 , meaning during the first loop it created a new key x and reinitialized the key during the second loop. It means that Python is interpreting x as a literal.

Is there anyway to have new_dict store 'a': 1 and 'b': 2 ?

This worked for me:

$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06) 
>>> d1 = {'a':1,'b':2}
>>> d2 = {}
>>> for k,v in d1.items():
...     if True:
...             d2[k] = v
... 
>>> d2
{'a': 1, 'b': 2}

You would just replace if True with your condition.

See here for some more info on looping over dictionaries: https://docs.python.org/3/tutorial/datastructures.html#looping-techniques

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM