sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
keys = ["name", "salary"]
newDict = { k: sampleDict[k] for k in keys}
print(newDict)
Asked
Active
Viewed 193 times
-1

MatsLindh
- 49,529
- 4
- 53
- 84
-
1What are you trying to extract here?? Can you show us the expected output? – Ajay A Jan 06 '21 at 10:02
-
Are you asking how sampleDict[k] returns the appropriate value? – Niteya Shah Jan 06 '21 at 10:04
-
What is your question? The new dictionary is generated using [dictionary comprehension](https://stackoverflow.com/questions/14507591/python-dictionary-comprehension), where the keys you've given it "transfers" the key/value pairs to a new dictionary. – MatsLindh Jan 06 '21 at 10:05
-
Maybe [this](https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension) helps? – costaparas Jan 06 '21 at 10:07
-
To `extract` values from a Python dictionary, you have to provide the key, e.g., `print(newDict["name"])` should print `"Kelly"` – anurag Jan 06 '21 at 10:16
1 Answers
1
It might be clearer what's happening if you avoid using dictionary comprehension (where the loop happens inside {}
.
The new dictionary is generated by { k: sampleDict[k] for k in keys}
, but we can rewrite that to be more explicit:
sample_dict = {"name": "Kelly", "age":25, "salary": 8000, "city": "New york"}
keys_to_keep = ["name", "salary"]
new_dict = {}
for key in keys_to_keep:
new_dict[key] = sample_dict[key]
print(new_dict)
In effect, for each key referenced in keys_to_keep
, copy the existing value from sample_dict
and store it under the same key in new_dict
.

MatsLindh
- 49,529
- 4
- 53
- 84