Reputation: 41
How would I successfully run a for loop through this so it prints like so.
names = {"James" : "18",
"Bob" : "19",
"adam": "39"
}
I want it to output as so:
Name1 = {"James" : "18"}
Name2 = { "Bob" : "19"}
Name3 = { "adam": "39"}
I have tried using for loops but I have been very unsuccessful. I have tried:
names.items()
returns:
dict_items([('adam', '39'), ('Bob', '19'), ('James', '18')])
but I need it to return in separate dictionaries as shown above.
Upvotes: 0
Views: 243
Reputation: 64318
for i, (k,v) in enumerate(names.items(), 1):
print('Name%d = %r' % (i, {k:v}))
Name1 = {'Bob': '19'}
Name2 = {'adam': '39'}
Name3 = {'James': '18'}
Note dictionaries are not ordered, so the order here is arbitrary. If you need specific ordering, you can create names
as an OrderedDict
to start with, and this code will do what you want.
EDIT: since you mentioned you need to store duplicate keys, you can do it like this:
names = [("James", "18"),
("Bob", "9"),
("adam", "39")]
for i, (k,v) in enumerate(names, 1):
print('Name%d = %r' % (i, {k:v}))
Upvotes: 1