简体   繁体   English

从 JSON 文件中的字典列表返回值

[英]Return values from a list of dictionaries in a JSON file

I have a JSON file and it has a list of dictionaries.I want to return only the subjects that are grater than 5.The JSON file is:我有一个 JSON 文件,它有一个字典列表。我只想返回大于 5 的主题。JSON 文件是:

{
    "email":"mortonfitzgerald@ontagene.com",
    "courses": [
        {"CS": 10},
        {"Maths": 3},
        {"Data Analysis": 9},
        {"Java":4},
        {"C":8}
    ]
}

Desired output is:所需的 output 是:

["CS:10 ...

You can use the Python JSON module to parse the JSON into an object.您可以使用 Python JSON 模块将 JSON 解析为 ZA8CFDE6331149EB2AC96B8F。 Then you can filter the list based on that object.然后您可以根据该 object 过滤列表。

import json

with open('data.json', 'r') as json_file:
    # parse string and get the courses part
    courses = json.loads(json_file.read())['courses']

    # convert single-entry dictionaries to tuples
    courses = [list(course.items())[0] for course in courses]

    # filter the courses based on the condition
    filtered_courses = list(filter(lambda course: course[1] > 5, courses))

    # prints [('CS', 10), ('Data Analysis', 9), ('C', 8)]
    print(filtered_courses)
    # prints {'CS': 10, 'Data Analysis': 9, 'C': 8}
    print(dict(filtered_courses))

Here is another way to do it without array filter using for loop:这是另一种不使用 for 循环进行数组过滤的方法:

import json

# this is the raw JSON loaded from a file
JSON = """
{
    "email":"mortonfitzgerald@ontagene.com",
    "courses": [
        {"CS": 10},
        {"Maths": 3},
        {"Data Analysis": 9},
        {"Java":4},
        {"C":8}
    ]
}
"""
# Loading coureses as json object
courses_json = json.loads(JSON)
# Selecting the courses list
courses = courses_json['courses']

# Empty list which will be populated by the filtered courses
filtered_courses = []

for index in range(len(courses)):
    for key in courses[index]:
        if courses[index][key] > 5:
            filtered_courses.append(key)

print(filtered_courses)

If you okay with a bit complex logic and are searching for shortcodes, I would suggest using a map and filter.如果您可以接受一些复杂的逻辑并且正在搜索简码,我建议您使用 map 和过滤器。 This will make your code a lot shorter and optimized.这将使您的代码更短和优化。 For your reference I am attaching a small piece of code for your case:-为了您的参考,我为您的案例附上了一小段代码:-

details =  {
    "email":"mortonfitzgerald@ontagene.com",
    "courses": [
        {"CS": 10},
        {"Maths": 3},
        {"Data Analysis": 9},
        {"Java":4},
        {"C":8}
    ]
}
values = list(map(lambda x: x[0],list(filter(lambda x: len(x) > 0, [list(filter(lambda key: d[key] > 5, d.keys())) for d in details["courses"]]))))

print(values)  --> ['CS', 'Data Analysis', 'C']

For a simple understanding, I am breaking the above one-liner code into chunks to give a brief overview of the power of map and filter function in python.为了简单理解,我将上面的单行代码分成块来简要概述 map 的强大功能,并在 python 中过滤 function。

  1. [list(filter(lambda key: d[key] > 5, d.keys())) for d in details["courses"]] [list(filter(lambda key: d[key] > 5, d.keys())) for d in details["courses"]]

    As every entry inside details["courses"] is a dictionary key, value pair.由于 details["courses"] 中的每个条目都是字典键值对。 I am using list comprehension to iterate the pair.我正在使用列表理解来迭代这对。

    " d " is those individual pairs. d ”是那些单独的对。 Then using the.keys() function I am trying to filter the " d " with a key whose value is greater than 5. This will return us a list of list of dictionary values.然后使用 the.keys() function 我正在尝试使用值大于 5 的键过滤“ d ”。这将返回我们一个字典值列表的列表。 Because of which the pair which doesn't satisfy the condition will have an empty list inside the result.因此,不满足条件的对将在结果中包含一个空列表。 To understand it better, I have attached the output of this command为了更好地理解它,我附上了这个命令的 output

res = [list(filter(lambda key: d[key] > 5, d.keys())) for d in details["courses"]] res = [list(filter(lambda key: d[key] > 5, d.keys())) for d in details["courses"]]

print(res)打印(分辨率)

[['CS'], [], ['Data Analysis'], [], ['C']] [['CS'], [], ['数据分析'], [], ['C']]

  1. Filtering out the empty list from the above output (res) " lambda x: len(x) > 0 " --> This lambda function will help in filtering out the list with size 0 Filtering out the empty list from the above output (res) " lambda x: len(x) > 0 " --> This lambda function will help in filtering out the list with size 0

filteredOutEmptyList = list(filter(lambda x: len(x) > 0, res)) filtersOutEmptyList = list(filter(lambda x: len(x) > 0, res))

print(filteredOutEmptyList)打印(filteredOutEmptyList)

  1. Now you just have to run a mapper function to pull out the first element of each list.现在你只需要运行一个映射器 function 来提取每个列表的第一个元素。

finalOutput = list(map(lambda x: x[0], filteredOutEmptyList)) finalOutput = list(map(lambda x: x[0], filteredOutEmptyList))

print(finalOutput)打印(最终输出)

There are lot more things and ways you can write the code using the map and filter function.您可以使用 map 和过滤器 function 编写代码,还有很多事情和方法。 It's very useful when dealing with iterable objects like lists, dictionaries, etc.在处理列表、字典等可迭代对象时非常有用。

Please reach out in the comments if you need any further clarification, I will try my best to help you out.如果您需要任何进一步的澄清,请在评论中联系,我会尽力帮助您。

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

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