簡體   English   中英

我試圖弄清楚如何添加到字典列表中,而不是創建一個字典列表列表

[英]I'm trying to figure out how to add to a list of dictionaries, rather than create a list of lists of dictionaries

我有一個函數 GetFunds,它返回一個字典。 它看起來像這樣:

[{“貨幣”:“BTC”,“可用”:0.460594115839,“保留”:0.0}]

對我來說,這看起來像是一個包含一本字典的列表。 我想在列表中添加更多詞典。 所以我試試這個代碼:

funds=GetFunds(1, "BTC")
funds=funds+(GetFunds(2, "BTC"))
funds=funds + GetFunds(1, "DIVI")
funds=funds + GetFunds(2, "DIVI")
print(funds)

結果是一個列表列表(我認為)

[ { "currency": "BTC", "available": 0.460594115839, "reserved": 0.0 } ] [ { "currency": "BTC", "available": 0.460594115839, "reserved": 0.0 } ][ { "currency ": "BTC", "available": 2.002708880342, "reserved": 0.449841884826 } ][ { "currency": "DIVI", "available": 6966346.17416024, "reserved": "currency": "DIVI": [VI] ", "可用": 6285691.0243108, "保留": 795457.15508981 } ]

但我想我想要一個包含 4 個元素的列表,每個元素都是一個字典......一組方括號

我試過簡單地使用“+”,我試過 .append,btu 我想那只是用於字符串

如上所示

我想要一個包含多個詞典的列表。

這是因為有字符串,所以使用json.loads

import json
funds=json.loads(GetFunds(1, "BTC"))
funds=funds + json.loads(GetFunds(2, "BTC"))
funds=funds + json.loads(GetFunds(1, "DIVI"))
funds=funds + json.loads(GetFunds(2, "DIVI"))
print(funds)

或者不那么推薦,使用ast.literal_eval

import ast
funds=ast.literal_eval(GetFunds(1, "BTC"))
funds=funds + ast.literal_eval(GetFunds(2, "BTC"))
funds=funds + ast.literal_eval(GetFunds(1, "DIVI"))
funds=funds + ast.literal_eval(GetFunds(2, "DIVI"))
print(funds)

如果結果是一個列表,它應該可以工作:

a = {'a' : 1, 'b' : 2}
b = {'c' : 3, 'd' : 4}
aa = [a]
aa.extend([b])
aa

結果:

 [{'b': 2, 'a': 1}, {'c': 3, 'd': 4}]

所以:

funds=GetFunds(1, "BTC")
funds.extend((GetFunds(2, "BTC")))

應該管用。

否則檢查它是否有效地是一個列表(看起來是這樣)。

type(aa)
<class 'list'>

我沒有足夠的聲譽發表評論,所以我發布了一個答案。

通過查看您發布的第二個片段,很明顯 GetFunds 返回一個字符串。 你是對的,當你看到看起來像 [{key: value}] 的東西時,我的第一個沖動也是“這是一個帶有一個字典的列表”。 但是,在您的第二個代碼段中,您有類似 [{key: value}][{key: value}] 的內容。 這顯然不是字典列表或字典列表。 字典列表看起來像 [{k: v}, {k: v}],而字典列表看起來像 [[{k: v}], [{k: v}]]。 這告訴我,當您認為將元素附加到列表時,實際上是在連接兩個字符串(其中碰巧包含字符,使其看起來像是一個列表,最有可能與 JSON 一起使用)。 注意左方括號和右方括號是如何背靠背的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM