Home > Software design >  Python - how to dynamically add items to a dictionary
Python - how to dynamically add items to a dictionary

Time:09-05

How can I dynamically add items (or rows) to a dictionary?

Here's what I'm trying to do:

# Declare an empty dictionary that needs to be built
my_dictionary = {}

# A random list
my_list = ["item 1", "item 2", "item 3", "item 4", "item5"]

# Routine/Function to add KEY and VALUES to this dictionary
for index in range(len(my_list)):
    new_values = {"code": index, "item_name": my_list[index]}
    my_dictionary.update(new_values)
print(my_dictionary)

The problem is that the output is not what I was expecting. The print(my_dictionary) gives me:

   {'code': 4, 'item_name': 'item5'}

I was expecting all the dictionary values to be inserted in here. Instead, it only gives me the last iteration. So the update() method doesn't insert new values into a dictionary.. it only updates existing records. How then do I insert new values??

UPDATE:

I think what I need is a way to create a nested dictionary So I'm expecting:

my_dictionary = 

{ 
"code": ...,
"Value": ...,
},
{
"code:" ...,
"value": ...
}

etc..

CodePudding user response:

my_list = ["item 1", "item 2", "item 3", "item 4", "item5"]

for index in range(len(my_list)):
    my_dictionary[index] = my_list[index]
print(my_dictionary)

->{0: 'item 1', 1: 'item 2', 2: 'item 3', 3: 'item 4', 4: 'item5'}

If this isn't what you want, you need to update your question with what you want your question to be.

CodePudding user response:

Another way is using dictionary comprehensions

{index:val for index, val in enumerate(my_list)}

CodePudding user response:

Not sure exactly what the output should be as it's not clear from the question. However, if you want a dictionary where the keys are the index positions from the list then:

my_list = ["item 1", "item 2", "item 3", "item 4", "item5"]

dict_ = dict(enumerate(my_list))

print(dict_)

Output:

{0: 'item 1', 1: 'item 2', 2: 'item 3', 3: 'item 4', 4: 'item5'}

Following an edit to the question it appears that this is what's needed:

my_output = [{'code': i, 'item_name': n} for i, n in enumerate(my_list)]

print(my_output)

Which gives:

[{'code': 0, 'item_name': 'item 1'}, {'code': 1, 'item_name': 'item 2'}, {'code': 2, 'item_name': 'item 3'}, {'code': 3, 'item_name': 'item 4'}, {'code': 4, 'item_name': 'item5'}]

CodePudding user response:

that is because the keys of a dictionary are unique, and thus you cannot have different values for the same key. so in every iteration of your for loop you overwrite the previous value. you can have a list of dictionaries with the same keys.

print(["data":{"code": index, "item_name":val} for index, val in enumerate(my_list)])
[{'code': 0, 'item_name': 'item 1'},
 {'code': 1, 'item_name': 'item 2'},
 {'code': 2, 'item_name': 'item 3'}, 
 {'code': 3, 'item_name': 'item 4'}, 
 {'code': 4, 'item_name': 'item5'}]
  • Related