Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update dictionary with dynamic keys and values in python

Tags:

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

like image 958
user850287 Avatar asked Dec 13 '12 12:12

user850287


People also ask

Can we update key-value in dictionary in Python?

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.

How do you update a list of values in a dictionary?

Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key']. append('value')


2 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))} 
like image 171
NPE Avatar answered Sep 23 '22 05:09

NPE


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 
like image 36
HelpNeeder Avatar answered Sep 25 '22 05:09

HelpNeeder