简体   繁体   中英

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.

my JSON file looks like this:

{"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.

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.

import json

The question implies we are getting input directly from the user, so we can use the input() function to gather that data. 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. 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 .

When we open() the file and I am choosing to refer to the opened file as fin . Then we pull out the content that is stored under the users key (that value happens to be a list of people).

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. 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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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