Home > OS >  How to turn an existing list into a key-value pair for a dictionary in Python?
How to turn an existing list into a key-value pair for a dictionary in Python?

Time:01-25

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!

CodePudding user response:

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:

add a cat

cats.append('Bob')

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.

add a new key to the dict

aniamls["dogs"] = ["Martin", ...]

CodePudding user response:

So based on your comment: "However, I don't want the [] and {} symbols to be printed"

As Iain mentions, this is a bit weird, but we can accomplish this in the following way, if you insist:

cats = ["Mary", "Snuggles", "Susan"]
rabbits = ["Cottonball", "Snowflake", "Fluffy"]

animals = {
  "cats": cats,
  "rabbits": rabbits
}

l=[]
for k,v in animals.items():
    l.append("\'{}\' : \"{}\"".format(k, "\", \"".join(v)))

print(", ".join(l))

Output:

'cats' : "Mary", "Snuggles", "Susan", 'rabbits' : "Cottonball", "Snowflake", "Fluffy"
  •  Tags:  
  • Related