深入研究Python字典,一次升级

时间:2019-02-17 04:48:32

标签: python dictionary

这似乎应该很容易,但我无法弄清楚。这是从JSON文件加载到此处的片段:

with open('states.json') as f:
    data = json.load(f)

如何仅打印状态名称?或者只是名称和缩写?

{
    "states": [
        {
            "name": "Alabama",
            "abbreviation": "AL",
            "area_codes": [
                "205",
                "251",
                "256",
                "334",
                "938"
            ]
        },
        {
            "name": "Alaska",
            "abbreviation": "AK",
            "area_codes": [
                "907"
            ]
        },
        {
            "name": "Arizona",
            "abbreviation": "AZ",
            "area_codes": [
                "480",
                "520",
                "602",
                "623",
                "928"
            ]
        }
}

尝试过:

print(data["states"])  #prints everything
print(data["states"]["name"]) #errors out
print(data["states"]["name"][0]) #prints just first record

也尝试过此方法,它会再次打印所有内容:

for state in data['states']:
    print(state)

1 个答案:

答案 0 :(得分:1)

应该遵循以下步骤:

state_names = [state["name"] for state in data["states"]]
print("\n".join(state_names))

或名称和缩写:

names_and_abbrev = ["{}: {}".format(state["abbreviation"], state["name"]) for state in data["states"]]
print("\n".join(names_and_abbrev))

结果:

AL: Alabama
AK: Alaska
AZ: Arizona