'How to turn an existing list into a key-value pair for a dictionary in Python?
Say I have two lists, for example:
cats = ["Mary", "Snuggles", "Susan"]
rabbits = ["Cottonball", "Snowflake", "Fluffy"]
I want to create dictionary animals, where "cats" and "rabbits" are the keys, and their corresponding lists are their values, like:
{cats : "Mary", "Snuggles", "Susan"
rabbits : "Cottonball", "Snowflake", "Fluffy"}
How can I go about doing this? I also want to make sure that I can add more names to the lists, and more keys to the dictionary later.
I appreciate the help!
Solution 1:[1]
You can just use the variables you already declared and make a dictionary:
cats = ["Mary", "Snuggles", "Susan"]
rabbits = ["Cottonball", "Snowflake", "Fluffy"]
animals = {
"cats": cats,
"rabbits": rabbits
}
If you want to push more cats or rabbits to the list:
to add a cat:
cats.append('Bob')
to add a rabbit:
rabbit.append('John')
The nice thing is that although you changed the lists, these changes are reflected in the dict, because the dict references them.
to add a new key to the dict
aniamls["dogs"] = ["Martin", ...]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gerda die gandalfziege |
