Home > other >  Create list of dictionaries with same keys
Create list of dictionaries with same keys

Time:10-21

I have a list of pandas series:

instaList =
[Bill        0.09
 Andy        12.89
 John        27.27
 Name: 5866, dtype: object,
 Bettia      0.32
 Tom         -10
 Levis       2
 Name: 4848, dtype: object,
 Shawn     4.61
 Tony      3.68
 Claude    0.69
 Name: 7448, dtype: object]

and I want to transform it into a list of dictionaries where the names from the list (e.g. "Bill") are the values from the key "name" and where the numbers (e.g. 0.09) are the values from the key "value":

 names = [
    {"name":"Bill","value":0.09},
    {"name":"Andy","value":12.88},
    {...}
 ]
 

I tried different things:

names = []
attributesDicts = {"name":"","value":""}

for insta in instaList:
    for index, value in insta.iteritems():
        attributesDicts["name"] = index
        attributesDicts["value"] = str(value)
        names.append(attributesDicts)

but I get duplicates or just the last data from the last series entry.

If I print attributesDicts I get the correct formatbut if I try to append it to a list it gives me duplicates or just the last entries. How would you do this?

Thank you very much.

CodePudding user response:

The problem is you create one dict "attributesDicts" and you pass the reference to the list. Then, you modify the same dictionary because the reference of the dict is the same for each iteration.

You should instanciate the dict in the for:

for insta in instaList:
for index, value in insta.iteritems():
    attributesDicts = {"name": index, "value": str(value)}
    names.append(attributesDicts)

CodePudding user response:

import pandas as pd

instaList = [pd.Series(name=5866, data=[['Bill', 0.09], ['Dan', 0.01], ['Lucia', 12.89]]),
             pd.Series(name=5866, data=[['Bettia', 0.29], ['Tom', 2.54], ['Tony', 4.89]])]

names = []

for pdseries in instaList:
    for i in pdseries.index:
        names.append({'name': pdseries[i][0], 'value': pdseries[i][1]})

print(names)

or as a one liner

import pandas as pd

instaList = [pd.Series(name=5866, data=[['Bill', 0.09], ['Dan', 0.01], ['Lucia', 12.89]]),
             pd.Series(name=5866, data=[['Bettia', 0.29], ['Tom', 2.54], ['Tony', 4.89]])]

names = [{'name': pdseries[i][0], 'value': pdseries[i][1]} for i in pdseries.index for pdseries in instaList]
  • Related