Search code examples
pythonpandaslistdictionaryseries

Create list of dictionaries with same keys


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.


Solution

  • 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)