Updating the dictionary with dynamic keys and values ​​in python

advertisements

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


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))}