如何使用JSON文件将所有特定元素名称添加到Python中的列表中

时间:2016-05-15 18:05:08

标签: python json python-2.7

使用Python 2.7和普通的JSON模块,我怎样才能把所有" accountName"列表中的变量?

{"accounts":[
    {   "accountName":"US Account", 
        "firstName":"Jackson"
    },
    {   "accountName":"Orange Account", 
        "firstName":"Micheal"
    },
    {   "accountName":"f safasf", 
        "firstName":"Andrew"
    }
]}

我试过了:

x = 0
accountsList = []

for Accounts['accountName'] in Accounts['accounts'][x]:
    accountsList.append(accountName)
    print accountsList
    x = x + 1

但我知道,这是一个非常错误的错误吗?

2 个答案:

答案 0 :(得分:1)

我使用列表理解,如下所示:

accountsList = [x["accountName"] for x in Accounts["accounts"]]

列表理解就像一个迷你for - 循环,当它通过另一个迭代时生成一个列表。

答案 1 :(得分:1)

使用列表理解,您可以:

[account["accountName"] for account in Accounts["accounts"]]
Out[13]: ['US Account', 'Orange Account', 'f safasf']

这与你正在做的类似,只有循环是:

accountsList = []
for account in Accounts["accounts"]: #because the "accounts" key gives a list
    accountsList.append(account["accountName"]) #under that list, there are 3 dictionaries and you want the key "accountName" of each dictionary