如何在Python中使用JSON fi将所有特定元素名添加到列表中

2024-05-12 20:10:47 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python2.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

但我知道这是非常错误的,有什么想法吗?你知道吗


Tags: 模块json列表accountfirstnameusaccountsorange
2条回答

我会使用一个列表,比如:

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

列表理解就像一个小的for-循环,它在遍历另一个iterable时生成一个列表。你知道吗

通过列表理解,您可以:

[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

相关问题 更多 >