update dictionary with dynamic keys and values in python
Remove the following line:
mydic = {i : o["name"]}
and add the following before your loop:
mydic = {}
Otherwise you're creating a brand new one-element dictionary on every iteration.
Also, the following:
mydic.update({i : o["name"]})
is more concisely written as
mydic[i] = o["name"]
Finally, note that the entire loop can be rewritten as a dictionary comprehension:
mydic = {i+1:o["name"] for i,o in enumerate(iterload(f))}
You could use len()
to insert the value:
#!/usr/bin/pythonqueue = {}queue[len(queue)] = {'name_first': 'Jon', 'name_last': 'Doe'}queue[len(queue)] = {'name_first': 'Jane', 'name_last': 'Doe'}queue[len(queue)] = {'name_first': 'J', 'name_last': 'Doe'}print queue
@NPE pointed out the problem in your code (redefining the dict on each iteration).
Here's one more way to generate the dict (Python 3 code):
from operator import itemgettermydict = dict(enumerate(map(itemgetter("name"), iterload(f)), start=1))
About the KeyError: '1'
: input()
returns a string in Python 3 but the dictionary mydict
expects an integer. To convert the string to integer, call int
:
nb_name = int(input("\nChoose the number of the name :"))