简体   繁体   English

在Python中创建字典列表(数据量大)

[英]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.我通过 json 导入了大量数据,我希望将这些数据存储为多个字典列表。

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):我使用的产品列表的格式如下(仅前 3 项):


['{"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.类类型显示 make_dictionary function 正在返回一个列表,其中的第一个元素是字典。

The output looks like this: output 看起来像这样:

[{'{"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?任何人都可以建议吗?

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. productlist 的每个元素都是一个字符串,这意味着在将它们附加到字典列表时必须将它们转换为字典。 The json.loads() method is used for parsing json data into a dictionary: json.loads() 方法用于将 json 数据解析为字典:

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".运行它会返回列表“bkpn1412”中第一个元素的用户名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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