I have the following list which I want to convert into a dictionary.
newData = ['John', 4.52, 'Jane', 5.19, 'Ram', 4.09, 'Hari', 2.97, 'Sita', 3.58, 'Gita', 4.1]
I want to create a dictionary like this:
newDict = [{'name': 'John', 'Height': 4.52},
{'name': 'Jane', 'Height': 5.19},
{'name': 'Ram', 'Height': 4.09},
{'name': 'Hari', 'Height': 2.97},
{'name': 'Sita', 'Height': 3.58},
{'name': 'Gita', 'Height': 4.1}]
What will be the easiest method to do this?
Enjoy:
newData = ['John', 4.52, 'Jane', 5.19, 'Ram', 4.09, 'Hari', 2.97, 'Sita', 3.58, 'Gita', 4.1]
newDict = [
{"name": name, "height": height}
for name, height in zip(newData[::2], newData[1::2])
]
print(newDict)
Here is quick list expansion you can do:
newDict = [{ 'name': newData[x], 'Height': newData[x + 1] } for x in range(0, len(newData), 2) ]
The trick is to use the step parameter with range
, which gives you every other element.
newDict = []
for i in range(0,len(newList),2):
newDict.append(
{'name':newList[i],
'hieght':newList[i+1]}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With