python – Adding item to Dictionary within loop

python – Adding item to Dictionary within loop

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

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.

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] = [value]

python – Adding item to Dictionary within loop

# Lets 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))
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

Leave a Reply

Your email address will not be published. Required fields are marked *