【问题标题】:Find key by value in python3 json在python3 json中按值查找键
【发布时间】:2020-09-23 18:30:26
【问题描述】:

我有一个 json 对象:users.json

{ 
  "1" :
       { "name" : "Jason" } , 
  "2" : 
       { "name" : "Alex" }
}

我有一个 python 函数,它接受一个名称作为输入,并且应该返回“id”。例如,如果我通过'Jason',它应该返回'1',如果我通过'Alex',它应该返回'2'。我知道这是一个简单的问题,但我真的被困住了......(而且有点懒于研究 python 字典......)这是我到目前为止所拥有的

def __init__(self):
    self.users_file = 'users.json'

def read_users_file(self):
    with open(self.users_file) as users_file:
        return json.load(users_file)

def get_user_id(self, name):  
    data = self.read_users_file()
    values = data.values()
    for val in data.values():
        if(name == val.get('name')):
            print('user found!')

谢谢!

【问题讨论】:

  • 我认为你的代码比你接受的答案更好。我看到的唯一问题是多余的values = data.values()

标签: python json python-3.x parsing file-io


【解决方案1】:
data = {
    "1":
    {"name": "Jason"},
    "2":
    {"name": "Alex"}
}


name = 'Jason'

for key in d:
    if (d[key]['name'] == name):
        print(key) ## output 1

或者以更 Pythonic 的方式:

for key, value in data.items():
    if name == value['name']:
        print(key)

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多