Pomegranate Molasses
Pomegranate Molasses

Reputation: 11

Creating a list of dictionaries in Python (large amount of data)

I have imported through json.loads a large volume of data which I wish to store as a number of lists of dictionaries.

I used this code:

def make_dictionary(l):
   list_of_dicts = []
   for i in range(0, len(l), 2):
       list_of_dicts.append({l[i]:l[i+1]})
   return list_of_dicts

products_dicts = make_dictionary(products_list)
print(products_dicts[:1])

The format of the products list I worked from is below (first 3 items only):


['{"Username": "bkpn1412", "DOB": "31.07.1983", "State": "Oregon", "Reviewed": ["cea76118f6a9110a893de2b7654319c0"]}\n', '{"Username": "gqjs4414", "DOB": "27.07.1998", "State": "Massachusetts", "Reviewed": ["fa04fe6c0dd5189f54fe600838da43d3"]}\n', '{"Username": "eehe1434", "DOB": "08.08.1950", "State": "Idaho", "Reviewed": []}\n']

A classtype reveals that the make_dictionary function is returning a list, the first element of which is a dictionary.

The output looks like this:

[{'{"Username": "bkpn1412", "DOB": "31.07.1983", "State": "Oregon", "Reviewed": ["cea76118f6a9110a893de2b7654319c0"]}\n': '{"Username": "gqjs4414", "DOB": "27.07.1998", "State": "Massachusetts", "Reviewed": ["fa04fe6c0dd5189f54fe600838da43d3"]}\n'}]

However I cannot access the keys in the dictionary and have been told that this data structure is not a list of dictionaries.

Can anyone advise?

Upvotes: 0

Views: 941

Answers (1)

Jona B
Jona B

Reputation: 36

Every element of your productlist is a string, which means these have to be converted to dictionaries when appending them to your list of dictionaries. The json.loads() method is used for parsing json data into a dictionary:

import json
productlist = ['{"Username": "bkpn1412", "DOB": "31.07.1983", "State": "Oregon", "Reviewed": ["cea76118f6a9110a893de2b7654319c0"]}\n', '{"Username": "gqjs4414", "DOB": "27.07.1998", "State": "Massachusetts", "Reviewed": ["fa04fe6c0dd5189f54fe600838da43d3"]}\n', '{"Username": "eehe1434", "DOB": "08.08.1950", "State": "Idaho", "Reviewed": []}\n']

def make_dictionary(l):
   list_of_dicts = []
   for i in l:
       list_of_dicts.append(json.loads(i))
   return list_of_dicts

products_dicts = make_dictionary(productlist)
print(products_dicts[0]["Username"])

Running this returns the username of the first element in your list "bkpn1412".

Upvotes: 1

Related Questions