简体   繁体   English

如何使用python获取字典列表中的特定键值

[英]How to get a particular key value in a list of dictionaries using python

Hello there this is my first stackoverflow question please bear with me.您好,这是我的第一个 stackoverflow 问题,请耐心等待。

my JSON file looks like this:我的 JSON 文件如下所示:

{"users":
 [
  {"name": "John Smith",
   "phone_num":"+104484932"
  },
  {"name": "Linda Ray",
   "phone_num": "+194387282"
  }
 ]
}

when given an input the script should look for the name in this list of dictionaries and return the phone number, I have tried many resources, it might also look like a possible copy of this question.当给出输入时,脚本应该在这个字典列表中查找名称并返回电话号码,我尝试了很多资源,它看起来也可能是这个问题的副本。

Which it isn't, thanks for your help in advance.不是,感谢您提前提供帮助。

Load the json file into a python dict, then iterate over the users list.将 json 文件加载到 python 字典中,然后遍历users列表。

def myfunction(target_name):
    with open('file.json') as f:
        data = json.load(f)
        for user in data['users']:
            if user['name'] == target_name:
                return user['phone_num']

You can do it in a simple way like你可以用一种简单的方式来做

json = {"users":
 [
  {"name": "John Smith",
   "phone_num":"+104484932"
  },
  {"name": "Linda Ray",
   "phone_num": "+194387282"
  }
 ]
}

inp = input('Name: ')

print([i['phone_num'] for i in json['users'] if i['name'] == inp][0])

Tell me if its not working...告诉我它是否不起作用...

We don't have access to your code, so not sure what approach you are taking.我们无权访问您的代码,因此不确定您采用的是哪种方法。 Gonna presume that this is simple and barebones.假设这是简单的准系统。

If the file is json, it will need to be read in and that will require that we import the json library.如果文件是 json,则需要读入它,这将要求我们导入json库。

import json

The question implies we are getting input directly from the user, so we can use the input() function to gather that data.这个问题意味着我们直接从用户那里获得输入,所以我们可以使用input()函数来收集这些数据。 Here we are providing a prompt that will display on the screen when the script is run.在这里,我们提供了一个提示,该提示将在脚本运行时显示在屏幕上。

username = input("Please supply a name: ")

From there, we read in the json file which gets read in as a Python dictionary.从那里,我们读入json文件,该文件作为 Python 字典读入。 Since it is a dictionary (Python dict() ), we can drill down into it to get to the data we care about querying on specific keys to see the associated values .由于它是一个字典(Python dict() ),我们可以深入研究它以获取我们关心的数据,查询特定keys以查看相关values

When we open() the file and I am choosing to refer to the opened file as fin .当我们open()文件时,我选择将打开的文件称为fin Then we pull out the content that is stored under the users key (that value happens to be a list of people).然后我们提取存储在users键下的内容(该值恰好是一个人的list )。

with open('filename.json') as fin:
    book = json.load(fin)
    users = data['users']

Then we parse each user in the users list and check for matches to the username that was input earlier.然后我们解析用户列表中的每个用户并检查是否与之前输入的username匹配。 When it finds a match, it prints the corresponding phone number.当它找到匹配项时,它会打印相应的电话号码。

    for user in users:
        if user['name'] == username:
            print(user['phone_num'])

The script in total will look something like this:整个脚本看起来像这样:

import json

username = input("Please supply a name: ")

with open('filename.json') as fin:
    book = json.load(fin)
    users = data['users']

    for user in users:
        if user['name'] == username:
            print(user['phone_num'])

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

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