Appending a dictionary to a list in a loop
You need to append a copy, otherwise you are just adding references to the same dictionary over and over again:
yourlist.append(yourdict.copy())
I used yourdict
and yourlist
instead of dict
and list
; you don't want to mask the built-in types.
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] }
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.
How to append a multiple dictionaries to a list from a loop, python?
def func(*args):
list_of_dicts = []
for X, y in zip(X, y):
a_dict = make_your_a_dict() # what you do in your example
list_of_dicts.append(a_dict)
return list_of_dicts # check indentation level
maybe it works.
How to append dictionary to a list in loop
We're going to mix three important concepts to make this code really small and beautiful. First, a list comprehension, then, the zip method, and finally, the dict method, to build a dictionary out of a list of tuples:
my_list = [('a1', 'b1', 'c1', 'd1', 'e1'), ('a2', 'b2', 'c2', 'd2', 'e2')]
keys = ('key1', 'key2', 'key3', 'key4', 'key5')
final = [dict(zip(keys, elems)) for elems in my_list]
After that, the value of the final
variable is:
>>> final
[{'key3': 'c1', 'key2': 'b1', 'key1': 'a1', 'key5': 'e1', 'key4': 'd1'},
{'key3': 'c2', 'key2': 'b2', 'key1': 'a2', 'key5': 'e2', 'key4': 'd2'}]
Also, you can get elements of a certain dictionary using the position of the dictionary in the list and the key you're looking for, i.e.:
>>> final[0]['key1']
'a1'
how to iterate over list and append dictionary to another list
How about this simpler version. Instead, the replace you can simply add 'd'
to the string[1:]
-
[{'id':i,'new_id':'d'+i[1:]} for i in lst]
[{'id': '12233223', 'new_id': 'd2233223'},
{'id': '13232423', 'new_id': 'd3232423'},
{'id': '23453443', 'new_id': 'd3453443'}]
EDIT: just saw your if
condition. Update with that -
[{'id':i,'new_id':'d'+i[1:]} for i in lst if i[0] if i[0]=='1' and len(i)==8]
[{'id': '12233223', 'new_id': 'd2233223'},
{'id': '13232423', 'new_id': 'd3232423'}]
Python: Way to build a dictionary with a variable key and append to a list as the value inside a loop
Using collections.defaultdict
:
from collections import defaultdict
out = defaultdict(list)
for item in dic1:
out[item['Name']].append(item['id'])
print(dict(out))
Or, without any imports:
out = {}
for item in dic1:
out[item['Name']] = out.get(item['Name'], []) + [item['id']]
print(out)
Or, with a list comprehension:
out = {}
[out.update({item['Name']: out.get(item['Name'], []) + [item['id']]}) for item in dic1]
print(out)
Output:
{'John': [10, 20], 'Mark': [21], 'Matthew': [30], 'Luke': [11]}
Can't append all values to dictionary using for loop
try this
l = [(1,2),(3,4)]
a = {}
a['r'] = []
for i in l:
a['r'].append(i)
print(a)
or simply you can do
l = [(1,2),(3,4)]
a = {}
a['r'] = l
print(a)
this is the output
{'r': [(1, 2), (3, 4)]}
Related Topics
How to Make Sessions Timeout in Flask
Convert a Python Dict to a String and Back
Format Strings VS Concatenation
Changing User Agent in Python 3 for Urrlib.Request.Urlopen
Is There a Multi-Dimensional Version of Arange/Linspace in Numpy
Bin Size in Matplotlib (Histogram)
Putting Many Python Pandas Dataframes to One Excel Worksheet
How to Get Char from String by Index
Django Serializer Imagefield to Get Full Url
List of All Available Matplotlib Backends
When Is Not a Good Time to Use Python Generators
Attributeerror: Can Only Use .Dt Accessor with Datetimelike Values
Split String Based on a Regular Expression
Convert Year/Month/Day to Day of Year in Python
Printing a List of Objects of User Defined Class
Opencv Python: Cv2.Findcontours - Valueerror: Too Many Values to Unpack