I have a properties file that I am reading and converting it into a dictionary using json library in python "convertedDict = json.loads(properties)" :
[
{"a":"1"},
{"b":"2"},
{"c":"3"},
{"d":"4"},
{"e":"5"},
{"f":"6"}
]
I want to have an output returned like below, which I want to be dictionaries inside of a list. I also want to add the words "key" and "value" in the dictionaries:
[
{
"key": "a",
"value": "1"
},
{
"key": "b",
"value": "2"
},
{
"key": "c",
"value": "3"
},
{
"key": "d",
"value": "4"
},
{
"key": "e",
"value": "5"
},
{
"key": "f",
"value": "6"
}
]
Please advise if you know, thanks in advance
CodePudding user response:
You can make a simple list comprehension and create the dictionaries in that. Here's one way to do it:
l = [
{"a":"1"},
{"b":"2"},
{"c":"3"},
{"d":"4"},
{"e":"5"},
{"f":"6"}
]
[{"key":k, "value":v} for d in l for k, v in d.items()]
Which results in:
[{'key': 'a', 'value': '1'},
{'key': 'b', 'value': '2'},
{'key': 'c', 'value': '3'},
{'key': 'd', 'value': '4'},
{'key': 'e', 'value': '5'},
{'key': 'f', 'value': '6'}]