从嵌套字典中只获取内部键

时间:2015-04-13 09:32:22

标签: python-2.7

我在这种形式的json文件中有数据

 [
    {
        "FIRST NAME": "Nasim",
        "EMAIL": "ac@iaculisnec.net",
        "ADDLINE1": "855-8805 Nunc. Avenue",
        "CITY": "Masterton",
        "LOCATION":{"ADDLINE2":"855-8805",
                    "ADDLINE3":"Avenue",
                    "PIN":"100",
                    "ZIP":{"AREA":"5645",
                           "STREET":"hgh",
                           "MAIN":"87"
                    }}
    },
    {
        "FIRST NAME": "Xanthus",
        "EMAIL": "adipiscing.elit@tinciduntcongue.edu",
        "ADDLINE1": "357-4583 Curae; St.",
        "CITY": "Basildon",
        "LOCATION":{"ADDLINE2":"357-4583",
                    "ADDLINE3":"Curae; St.",
                    "PIN":"101",
                    "ZIP":{"AREA":"546",
                           "STREET":"yjtyj",
                           "MAIN":"56"
                   }}
    }

如何仅列出此表单中的键 的 FIRSTNAME 电子邮件 ADDLINE1 市 LOCATION {ADDLINE2,ADDLINE3,PIN,ZIP {AREA,街道,MAIN}}

我已经实现了这个

for key in row.iterkeys():
    print key 
    for items in row[key]:
        print items 

但是我和它一起得到了价值。即使深度增加,它也应该能够列出所有子键。 需要这种形式的输出

FIRSTNAME
LOCATION
  ADDLINE2
  ADDLINE3
  PIN
  ZIP
    STREET
    MAIN
    AREA
ADDRESS
EMAIL

2 个答案:

答案 0 :(得分:0)

您可以尝试以下递归方法:

def get_keys(d):
    for key in d.iterkeys():
        yield key
        if isinstance(d[key], dict):
            yield list(get_keys(d[key]))

for row in data:
    print list(get_keys(row))

如果data是您的嵌套字典,则会为您提供此输出:

['ADDLINE1', 'FIRST NAME', 'LOCATION', ['ADDLINE3', 'ADDLINE2', 'ZIP', ['STREET', 'MAIN', 'AREA'], 'PIN'], 'EMAIL', 'CITY']
['ADDLINE1', 'FIRST NAME', 'LOCATION', ['ADDLINE3', 'ADDLINE2', 'ZIP', ['STREET', 'MAIN', 'AREA'], 'PIN'], 'EMAIL', 'CITY']

请注意,键的顺序可能与原始字典中的顺序不同,因为无法保证d.iterkeys()(或任何其他类似方法)生成键的顺序。

如果你想以问题中显示的格式将它们变成字符串,你可以使用:

def to_string(keys):
    return " ".join("{" + to_string(key) + "}" if isinstance(key, list) else key.replace(" ", "") for key in keys)

结果为ADDLINE1 FIRSTNAME LOCATION {ADDLINE3 ADDLINE2 ZIP {STREET MAIN AREA} PIN} EMAIL CITY。请注意,这会将FIRST NAME之类的密钥折叠为FIRSTNAME(正如您在示例中所做的那样),否则您需要使用除" "之外的其他分隔符,例如", ".join(...)。请改用{{1}}。就个人而言,我宁愿将其保留为列表,将其转换为字符串。

答案 1 :(得分:0)

递归解决方案可能是:

def getkeys(x):
    result = []
    for k, v in x.items():
        result.append(k)
        if isinstance(v, dict):
            result += getkeys(v)
    return result

map(getkeys, your_json_objects_list)
  

[[' ADDLINE1',' FIRST NAME',' LOCATION',' ADDLINE3',' ADDLINE2' ,' ZIP',   ' STREET',' MAIN',' AREA',' PIN',' EMAIL',' CITY& #39;],[' ADDLINE1',   ' FIRST NAME',' LOCATION',' ADDLINE3',' ADDLINE2',' ZIP',' STREET&#39 ;,   ' MAIN',' AREA',' PIN',' EMAIL' CITY' CITY' ]