2016-05-15 14 views
0

Python 2.7と通常のJSONモジュールを使用して、「accountName」変数をすべてリストに入れる方法を教えてください。JSONファイルを使用してPythonのリストに特定の要素名をすべて追加する方法

{"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 

しかし、私は、それは非常に間違っている任意のアイデアを知っていますか?

答えて

1

私はこのように、リストの内包表記を使用したい:

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

リストの内包は、それが別の反復可能を通過すると、リストを生成し、ミニfor -loopのようなものです。リスト内包して

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 
関連する問題