Adding item to Dictionary within loop
Asked Answered
D

5

20

Below data is grasped from webpage and containing entries as below(like a table with many rows):

entry1: key1: value1-1, key2: value2-1, key3: value3-1
entry2: key1: value1-2, key2: value2-2, key3: value3-2
entry3: key1: value3-1, key2: value2-3, key3: value3-3
......
entry100: key1: value100-1, key2: value100-2, key3: value100-3

how can I use a dictionary to store this data? the data is from a list thus the 'dictionary append' should be done within a loop...

here is my current solution:

case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list.update(case)

but the case_list in the end only contains the last case entry... Can somebody please help me on this? I would expect the case_list containing 100 entries w/o any overwriting among entries, and I will need to store it to DB afterwards.

Deloresdeloria answered 2/7, 2015 at 10:14 Comment(4)
is each entry a list, or can you show what entries_list has?Tswana
Whats the format of key1: value1-1, key2: value2-1, key3: value3-1 and how you store your entries within file?Anisaanise
What's the expected result? Currently you're just overwriting all the keys on each iteration.Malcah
case_list.update(case) will update case_list with new key/value pairs from case and overwrite values for the existing case.Rennet
T
56

In your current code, what Dictionary.update() does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.

If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list as a list and then append case to it (instead of update) .

Example -

case_list = []
for entry in entries_list:
    case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
    case_list.append(case)

Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1 or entry2 , etc and the value being the corresponding dictionary for that entry.

case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list[entryname] = case  #you will need to come up with the logic to get the entryname.
Tswana answered 2/7, 2015 at 10:24 Comment(0)
M
15

As per my understanding you want data in dictionary as shown below:

key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3

for this you can use list for each dictionary keys:

case_list = {}
for entry in entries_list:
    if key in case_list:
        case_list[key1].append(value)
    else:
        case_list[key1] = [value]
Mccafferty answered 2/7, 2015 at 10:32 Comment(0)
K
3
# Let's add key:value to a dictionary, the functional way 
# Create your dictionary class 
class my_dictionary(dict): 
    # __init__ function 
    def __init__(self): 
        self = dict()   
    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value 
# Main Function 
dict_obj = my_dictionary() 
limit = int(input("Enter the no of key value pair in a dictionary"))
c=0
while c < limit :   
    dict_obj.key = input("Enter the key: ") 
    dict_obj.value = input("Enter the value: ") 
    dict_obj.add(dict_obj.key, dict_obj.value) 
    c += 1
print(dict_obj) 
Kozloski answered 12/7, 2019 at 11:39 Comment(0)
J
1

Simpler Solution - use copy() instead of directly appending the dict in list

case_list = []
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list.append(case.copy())

This will not have any duplicates.

Janie answered 24/3, 2021 at 15:49 Comment(0)
C
0

Here is an example for adding an item to a dictionary in a loop.

events_list = [['2024-02-24', 'Prague Python Pizza 2024'],
               [ '2024-02-24', 'Django Girls Ho'],
               ['2024-02-25', 'PyCon PH 2024'],
               ['2024-02-29', 'PyLadies Amsterdam'],
               ['2024-03-04', 'PyCon Namibia 2024']]
event_dict = {}
for event in events_list:
    time = event[0]
    name = event[1]
    event_dict[events_list.index(event)] = {
        "Time": time,
        "Name": name
    }
print(event_dict)
Consecutive answered 22/2 at 1:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.