Skip to content Skip to sidebar Skip to footer

Python List With Dict Should Have Same Key

I want my_list should have a dict with same key but with multiple values my_list = [] my_dict = {} old_list = ['1','2','3','4','5'] for i in old_list: my_dict['Cidr'] = i m

Solution 1:

Your dict is getting mutated - you only have one dict and every loop you just change the value at key 'Cidr'. The array contains 5 references to the same dict.

What you need to do is create a new dict each time you do the loop:

my_list = []
old_list = ['1','2','3','4','5']
for i in old_list:
    my_dict = {}
    my_dict['Cidr'] = i
    my_list.append(my_dict)
print(my_list)

That way each element in the array will have it's own dictionary.

Solution 2:

Try this

my_list = []
old_list = ['1','2','3','4','5']
for i in old_list:
    my_dict = {}
    my_dict['Cidr'] = i
    my_list.append(my_dict)
print(my_list)

Solution 3:

old_list = ['1','2','3','4','5']
my_list = [{'Cidr': i} for i in old_list]

Solution 4:

Try use a copy.deepcopy.

importcopy
my_list = []
my_dict = {}
old_list = ['1','2','3','4','5']
for i in old_list:
    my_dict['Cidr'] = i
    my_list.append(copy.deepcopy(my_dict))
print my_list

Post a Comment for "Python List With Dict Should Have Same Key"