简体   繁体   中英

Creating a list of dictionaries from a list of list

I'm currently stuck facing some issue with creating a list of dictionaries from a list of lists. I'm confused with how to append each dictionary to empty list(not in my code). I've known there should be some code after loop processing, but I wasn't able to find out what it is.

l_members = [['Jhon', '19', 'male'],
       ['Takeru', '20', 'male'],
       ['Yuri', '22', 'female']
      ]

d_members = {}

for i in range(len(l_members)):
  d_members['name'] = l_members[i][0]
  d_members['age'] = l_members[i][1]
  d_members['sex'] = l_members[i][2]
  l_members.append(d_members)

print(d_members)

Here's a result of print(d_members)

{'name': 'Yuri', 'age': '22', 'sex': 'female'}

my expectation of the result is like below

[{'name': 'Jhon', 'age': '19', 'sex': 'male'},
 {'name': 'Takeru', 'age': '20', 'sex': 'male'},
 {'name': 'Yuri', 'age': '22', 'sex': 'female'}]

I would appreciate your help, thanks:)

Maybe a list comprehension might work:

d_members = [
   { 'name': name, 'age': age, 'sex': sex } 
   for name, age, sex in l_members
]
  • print the list, not the dict you created print(l_members)
  • create d_members in the loop, to avoid using the same again and again
  • then reassign to the i box, don't append because it'll only add it
for i in range(len(l_members)):
    d_members = {}
    d_members['name'] = l_members[i][0]
    d_members['age'] = l_members[i][1]
    d_members['sex'] = l_members[i][2]
    l_members[i] = d_members
print(l_members)

Here are some shorten ways with enumerate , I put some to show you the possiblities

for i in range(len(l_members)):
    l_members[i] = {'name': l_members[i][0], 'age': l_members[i][1], 'sex': l_members[i][2]}

for i, member in enumerate(l_members):
    l_members[i] = {'name': member[0], 'age': member[1], 'sex': member[2]}

for i, (name, age, sex) in enumerate(l_members):
    l_members[i] = {'name': name, 'age': age, 'sex': sex}

You can also use a list-comprehension to avoid using the indices and rebuilt directly the list, along with dict+zip to create the dict:

l_members = [dict(zip(['name', 'age', 'sex'], member)) for member in l_members]
# another one
l_members = [{'name': name, 'age': age, 'sex': sex} for (name, age, sex) in l_members]

As I've mentioned in the comments, this is because your last line of code which prints the value actually prints the d_members variable which will be the last value of the for-loop. You should instead be printing out the l_members variable which you appended the values to in your for-loop.

Additionally, you'll robably find out that the previous records still exist when you print l_members , so you'll have to either:

  1. Remove the initial entries once you're done with the for loop (using list slicing):

     l_members = l_members[3:]
  2. Override the value for each iteration of the for loop:

     l_members[i] = d_members
  3. Or store the results in a new variable:

     ld_members = [] # in your for loop: ld_members.append(d_members)

Just append the dict to a new list inside the loop as below

list_of_dicts = []
for i in range(len(l_members)):
    d_members = {}
    d_members['name'] = l_members[i][0]
    d_members['age'] = l_members[i][1]
    d_members['sex'] = l_members[i][2]
    list_of_dicts.append(d_members)

print(list_of_dicts)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM