字符串转换为字典而不是列表

字符串转换为字典而不是列表

本文介绍了将 JSON 字符串转换为字典而不是列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试传入一个 JSON 文件并将数据转换为字典.

到目前为止,这就是我所做的:

导入jsonjson1_file = open('json1')json1_str = json1_file.read()json1_data = json.loads(json1_str)

我期望 json1_data 是一个 dict 类型,但当我用 检查它时,它实际上是一个 list 类型> 类型(json1_data).

我错过了什么?我需要这是一本字典,以便我可以访问其中一个键.

解决方案

你的 JSON 是一个数组,里面只有一个对象,所以当你阅读它时,你会得到一个里面有字典的列表.您可以通过访问列表中的第 0 项来访问您的字典,如下所示:

json1_data = json.loads(json1_str)[0]

现在您可以像预期的那样访问存储在数据点中的数据:

datapoints = json1_data['datapoints']

如果有人可以咬我,我还有一个问题:我试图取这些数据点(即数据点[0][0])中第一个元素的平均值.只是为了列出它们,我尝试做 datapoints[0:5][0] 但我得到的只是包含两个元素的第一个数据点,而不是想要获得仅包含第一个元素的前 5 个数据点.有没有办法做到这一点?

datapoints[0:5][0] 不符合您的预期.datapoints[0:5] 返回一个只包含前 5 个元素的新列表切片,然后在它的末尾添加 [0] 将只包含第一个元素 从结果列表切片.你需要用来获得你想要的结果是一个列表理解::>

[p[0] for p in datapoints[0:5]]

这是计算均值的简单方法:

sum(p[0] for p in datapoints[0:5])/5.# 结果是 35.8

如果您愿意安装 NumPy,那就更简单了:

导入numpyjson1_file = open('json1')json1_str = json1_file.read()json1_data = json.loads(json1_str)[0]数据点 = numpy.array(json1_data['数据点'])avg = 数据点 [0:5,0].mean()# 平均现在是 35.8

, 运算符与 NumPy 数组的切片语法一起使用具有您最初期望的列表切片行为.

I am trying to pass in a JSON file and convert the data into a dictionary.

So far, this is what I have done:

import json
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)

I'm expecting json1_data to be a dict type but it actually comes out as a list type when I check it with type(json1_data).

What am I missing? I need this to be a dictionary so I can access one of the keys.

解决方案

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']


datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

这篇关于将 JSON 字符串转换为字典而不是列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:39