my_dict = {0: {'alpha': 1510, 'beta': 700, 'gamma': 500},
1: {'alpha': 1710, 'beta': 900, 'gamma': 700}}
This is my dictionary, I want to remove those 0 and 1 keys that you see there and have it become a list format like so
my_list = [{'alpha': 1510, 'beta': 700, 'gamma': 500},
{'alpha': 1710, 'beta': 900, 'gamma': 700}]
I want it that way so that I can get a clean JSON output like this
[
{
"alpha": 1510,
"beta": 700,
"gamma": 500
},
{
"alpha": 1710,
"beta": 900,
"gamma": 700
}
]
Any help would be greatly appreciated, Thanks in advance!
CodePudding user response:
Use .values
method of dict
:
my_list = list(my_dict.values())
print(my_list)
# Output
[{'alpha': 1510, 'beta': 700, 'gamma': 500},
{'alpha': 1710, 'beta': 900, 'gamma': 700}]
CodePudding user response:
I want to remove those 0 and 1 keys that you see there and have it become a list format like so
The solution @Corralien gave you should be able to do that.
I want it that way so that I can get a clean JSON output like this
For that, you can use Python's json
module and use the function dumps
. It's got an optional parameter indent
and setting it to 4 usually "beautifies" your json.
This code
import json
my_dict = {0: {'alpha': 1510, 'beta': 700, 'gamma': 500},
1: {'alpha': 1710, 'beta': 900, 'gamma': 700}}
my_json_string = json.dumps(list(my_dict.values()), indent=4)
print(my_json_string)
Outputs
[
{
"alpha": 1510,
"beta": 700,
"gamma": 500
},
{
"alpha": 1710,
"beta": 900,
"gamma": 700
}
]