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
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.
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')
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/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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With