update dictionary with dynamic keys and values in python

Question:

I have a dictionary and I want to insert keys and values dynamically but I didn’t manage to do it. The problem is that when I use the update method it doesn’t add a pair but it deletes the previous values so I have only the last value when printing the dictionary
here is my code

i = 0
for o in iterload(f):
    i=i+1
    mydic = {i : o["name"]}
    mydic.update({i : o["name"]})
    for k, v in mydic.items():
        print(k,v) 
print(mydic)

f is a file that i’m parsing with python code
as a result I get

{3: 'toto'}

which is the last element. is there a solution to have all the elements in my dictionary

Thanks in advance

I have another question

Now I need to chek if an input value equals a key from my dictionary and if so I need to get the value of this key to continue parsing the file and get other informations.

Here is my code :

f = open('myfile','r')
nb_name = input("nChoose the number of the name :")

for o in iterload(f):
    if o["name"] == mydic[nb_name]: 
        ...

I get a keyError

Traceback (most recent call last):
  File ".../test.py", line 37, in <module>
            if o["name"] == mydic[nb_name]: 
KeyError: '1'

I don’t understand the problem

Asked By: user850287

||

Answers:

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))}
Answered By: NPE

@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 itemgetter

mydict = 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 :"))
Answered By: jfs

You could use len() to insert the value:

#!/usr/bin/python

queue = {}

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
Answered By: HelpNeeder
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.