Home > Net >  How to create a list of separate dictionaries which are not all the same
How to create a list of separate dictionaries which are not all the same

Time:06-03

I want to create a list of Dictionary. I am not getting the desired output. Here is my code:

list = ['Frank','John', 'Mitchel','Melania','Samson','scophield']
dict = []

for i in list:
    name = {}
    for i in list:
        name["First_name"]= i
    dict.append(name)

print(dict)

As Output,I have this:

[{'First_name': 'scophield'}, {'First_name': 'scophield'}, {'First_name': 'scophield'}, {'First_name': 'scophield'}, {'First_name': 'scophield'}, {'First_name': 'scophield'}]

I am expecting something like this:

  [{'First_name': 'Frank'}, {'First_name': 'John'}, {'First_name': 'Mitchel'}, {'First_name': 'Melania'}, {'First_name': 'Samson'}, {'First_name': 'scophield'}]

How can I get the desire output?

CodePudding user response:

You don't need iterate twice, just do one time

list = ['Frank','John', 'Mitchel','Melania','Samson','scophield']
dict = []

for i in list:
    name = {}
    name["First_name"]= i
    dict.append(name)

print(dict)

Output:

[{'First_name': 'Frank'}, {'First_name': 'John'}, {'First_name': 'Mitchel'}, {'First_name': 'Melania'}, {'First_name': 'Samson'}, {'First_name': 'scophield'}]

CodePudding user response:

Just do:

namesList = ['Frank','John', 'Mitchel','Melania','Samson','scophield']
namesListOfDicts = [{"First_name": i} for i in namesList]


[{'First_name': 'Frank'}, {'First_name': 'John'}, {'First_name': 'Mitchel'}, {'First_name': 'Melania'}, {'First_name': 'Samson'}, {'First_name': 'scophield'}]
  • Related