从Python中嵌套的Dictionary获取数据

时间:2017-11-02 03:18:52

标签: python dictionary

我一直在尝试从python中的多级字典中提取数据 我从中提取的字典示例是:

{"family": {
"name": "Mary",
"age": "32",
"sex": "female",
"kids": [
  {
    "name": "jim",
    "age": "10",
    "sex": "male",
    "dob_year": "2007",
    "ssn": "123-23-1234"
  },
  {
    "name": "jill",
    "age": "6",
    "sex": "female",
    "dob_year": "2011",
    "ssn": "123-23-1235"
  }]}}


ss = test0["family"]["kids"]

def search(values, lookup):
    for k in values:
        for v in values:
            if lookup in v:
                return k
    return None
print search(ss, '201')

我的目标是在嵌套字典的值中搜索关键字(不精确)并返回完整字典或特定键的值,如" 23-23-1235"如果要求ssn。

需要它返回{"名称":" jill","年龄":" 6","性别&# 34;:"女性"," dob_year":" 2011"," ssn":" 123-23-1235&#34 ;}不同级别的请求值。

现在它只显示:{" name":" jim"," age":" 10","性别":"男性", " dob_year":" 2007"," ssn":" 123-23-1234"}

2 个答案:

答案 0 :(得分:0)

尝试这种方式:

test0 = {"family": {
"name": "Mary",
"age": "32",
"sex": "female",
"kids": [
  {
    "name": "jim",
    "age": "10",
    "sex": "male",
    "dob_year": "2007",
    "ssn": "123-23-1234"
  },
  {
    "name": "jill",
    "age": "6",
    "sex": "female",
    "dob_year": "2011",
    "ssn": "123-23-1235"
  }]}}


ss = test0["family"]["kids"]
def search(values, lookup):
    for k in values:
        if any(lookup in str(s) for s in k.values()):
            return k
    return None
print search(ss, '201')

它会打印出来:

{'age': '6', 'dob_year': '2011', 'name': 'jill', 'ssn': '123-23-1235', 'sex': 'female'}

答案 1 :(得分:0)

  

如果匹配两个结果怎么办?

如果它匹配多个结果但仍然只返回一个返回值,因为函数一次一个地返回一个内存所以解决方案是存储结果,比如使用列表存储结果,然后最后返回它,让我们看看它是否匹配两个结果然后问题:

简单的解决方案

 def search(values, lookup):
        for item in values:
            for key,value in item.items():
                if lookup in value:
                    return item
        return None
    print(search(ss, '20'))

它匹配两个结果,但输出为:

{'dob_year': '2007', 'ssn': '123-23-1234', 'sex': 'male', 'age': '10', 'name': 'jim'}

所以解决方案是:

def search(values, lookup):
    result = []

    for item in values:
        for key,value in item.items():
            if lookup in value:
                if item not in result:
                    result.append(item)

    if result:
        return result
    else:
        return None
print(search(ss, '20'))

输出:

[{'ssn': '123-23-1234', 'sex': 'male', 'dob_year': '2007', 'age': '10', 'name': 'jim'}, {'ssn': '123-23-1235', 'sex': 'female', 'dob_year': '2011', 'age': '6', 'name': 'jill'}]