'How to convert from tuple to dictionary in python, for the following code?
({'timestamp': 1649767465, 'id': 48}, {'timestamp': 1649766359, 'id': 48}, {'timestamp': 1649766249, 'id': 48}, {'timestamp': 1649765101, 'id': 48}, {'timestamp': 1649747642, 'id': 48})
Solution 1:[1]
({'timestamp': 1649767465, 'id': 48}, {'timestamp': 1649766359, 'id': 48}, {'timestamp': 1649766249, 'id': 48}, {'timestamp': 1649765101, 'id': 48}, {'timestamp': 1649747642, 'id': 48})
The above is a tuple of dictionaries. Lets take the first one i.e., {'timestamp': 1649767465, 'id': 48}, has two key value pairs.
The tuple has no key to be made into a dictionary. Hence it will not be possible to make a nested dictionary in the above example.
However, it could be converted into a list of dictionaries (if you want to update your variables later).
variable = [{'timestamp': 1649767465, 'id': 48}, {'timestamp': 1649766359, 'id': 48}, {'timestamp': 1649766249, 'id': 48}, {'timestamp': 1649765101, 'id': 48}, {'timestamp': 1649747642, 'id': 48}]
Now to get any element, just loop through the list and get the desired one. Every element is a dictionary hence the value can be called using key.
For Example,
for v in variable:
print(v['timestamp'])
print(v['id'])
Output
1649767465
48
1649766359
48
1649766249
48
1649765101
48
1649747642
48
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 | CoffeeBeans |
