'Append dict at same time python
I want to append elements to an empty dictionary in python. For a current frame I am attributing two keys: 'ID' and 'Coordinates'. My problem is when I am appending the values, e.g
df={}
for i in range:
df[i]['ID'].append(ID.values)
df[i]['coordinates'].append(coordinates.values)
The output is something like this
{'ID': [ID.values], 'coordinates': [coordinates.values]}}.
But what is supposed to get is something like this
{'ID': [ID.value], 'coordinate': [coordinate.value],
'ID': [ID.value], 'coordinate': [coordinate.value],...}
I need the code to do the append at the same time, so the first ID matches with the first coordinate, the second ID with the second coordinate, and so on.
Solution 1:[1]
You can use the zip built-in function to transform the two arrays into an array of pairs, then call the dict function to generate your dictionary:
df = dict(zip(ID.values, coordinates.values))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lemon |
