5

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?

3 Answers3

8

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)
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95
5

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.

2ps
  • 15,099
  • 2
  • 27
  • 47
4
newDict = []
for i in range(0,len(newList),2):
    newDict.append(
        {'name':newList[i],
        'hieght':newList[i+1]}
    )
harshil9968
  • 3,254
  • 1
  • 16
  • 26