Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dictionary with new KEY with data from list? [duplicate]

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?

like image 698
Nabin Jaiswal Avatar asked Dec 20 '16 07:12

Nabin Jaiswal


3 Answers

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)
like image 141
Fomalhaut Avatar answered Oct 14 '22 17:10

Fomalhaut


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.

like image 33
2ps Avatar answered Oct 14 '22 16:10

2ps


newDict = []
for i in range(0,len(newList),2):
    newDict.append(
        {'name':newList[i],
        'hieght':newList[i+1]}
    )
like image 23
harshil9968 Avatar answered Oct 14 '22 17:10

harshil9968