How to create a dictionary with a new key with data from the list?

I have the following list that I want to convert to 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 would be the easiest way to do this?

+5
source share
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) 
+6
source

The following is a quick list extension:

 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 all the other elements.

+5
source
 newDict = [] for i in range(0,len(newList),2): newDict.append( {'name':newList[i], 'hieght':newList[i+1]} ) 
+2
source

Source: https://habr.com/ru/post/1261551/


All Articles