简体   繁体   English

如何转换字典列表中的字典?

[英]How to convert dict in list of dicts?

{'BTC': [(None, None), (1, -0.4), (3, 0.3333333333333333), (0, 0.75), (1, None)], 'ETH': [(None, None), (0, 0.5), (0, 0.3333333333333333), (0, -0.1), (2, None)]}

in this 在这

 [{'BTC': (None, None), 'ETH': (None, None)}, {'BTC':  (1, -0.4), 'ETH': (0, 0.5)}, {'BTC': (3, 0.3333333333333333), 'ETH': (0, -0.1)}, {'BTC': (1, None), 'ETH':  (2, None)}]

If I use lists, I can use zip function to easy convert, but how can I do this using dictionary? 如果使用列表,则可以使用zip函数轻松进行转换,但是如何使用字典来做到这一点?

Assuming you know the length of the list, then this should work: 假设您知道列表的长度,那么应该可以:

[{z:xx[z][i] for z in xx.keys()} for i in range(5)]

Output 输出量

[{'BTC': (None, None), 'ETH': (None, None)}, {'BTC': (1, -0.4), 'ETH': (0, 0.5)}, {'BTC': (3, 0.3333333333333333), 'ETH': (0, 0.3333333333333333)}, {'BTC': (0, 0.75), 'ETH': (0, -0.1)}, {'BTC': (1, None), 'ETH': (2, None)}]

Previous answer 先前的答案

[{z:xx[z][i]} for z in xx.keys() for i in range(5)]

Output 输出量

[{'BTC': (None, None)}, {'BTC': (1, -0.4)}, {'BTC': (3, 0.3333333333333333)}, {'BTC': (0, 0.75)}, {'BTC': (1, None)}, {'ETH': (None, None)}, {'ETH': (0, 0.5)}, {'ETH': (0, 0.3333333333333333)}, {'ETH': (0, -0.1)}, {'ETH': (2, None)}]

Assuming all the list are of the same length, you could do: 假设所有列表的长度相同,则可以执行以下操作:

d = {'BTC': [(None, None), (1, -0.4), (3, 0.3333333333333333), (0, 0.75), (1, None)],
     'ETH': [(None, None), (0, 0.5), (0, 0.3333333333333333), (0, -0.1), (2, None)]}

table = {}
for key, values in d.items():
    for i, value in enumerate(values):
        table.setdefault(i, {})[key] = value

result = list(table.values())
print(result)

Output 输出量

[{'BTC': (None, None), 'ETH': (None, None)}, {'BTC': (1, -0.4), 'ETH': (0, 0.5)}, {'BTC': (3, 0.3333333333333333), 'ETH': (0, 0.3333333333333333)}, {'BTC': (0, 0.75), 'ETH': (0, -0.1)}, {'BTC': (1, None), 'ETH': (2, None)}]

The idea is to create a dictionary where the key are indices and the values are the expected dictionaries. 这个想法是创建一个字典,其中的键是索引,值是期望的字典。

My guess is that it has to do with how the dict and list are hashed. 我的猜测是,它与字典和列表的散列方式有关。 Dict has key values, and orders itself how it sees fit, lists don't. Dict具有键值,并按其自身顺序排列自己的显示方式,而列表则不然。 You're also using tuples in here too though, so that might affect it. 您也可以在这里使用元组,这样可能会影响它。 Is there a reason you're structuring it this way? 您以这种方式进行构造是否有原因? Seems like it could be more efficiently done with just lists and dicts. 似乎仅使用列表和字典可以更有效地完成它。

Either way, you'd just be a lot better off using pandas. 无论哪种方式,使用熊猫都会让您的生活变得更好。 Especially if you're using it for crypto-currency, or any other financial data. 特别是当您将其用于加密货币或任何其他财务数据时。 It'll do a lot for you. 它会为您做很多事。

Let's say tickers is a list of cryptocurrency coins. 假设股票行情是加密货币硬币的列表。 and then we have a dict of the financial data using the range(len(tickers)) of tickers as the key. 然后我们使用代码范围(len(tickers))作为键来决定财务数据。

import pandas as pd

tickers=['BTC','ETC','ETH','LTC','XRP', etc.]

financial_data={}
for i in range(len(tickers)):
    financial_data[i]= get_finince_data(tickers[i])
                        #^this isn't an actual function. just an example 
                        #to represent whatever you're using to pull data
financial_data= pd.DataFrame(financial_data)

or, if you really like the structure that you're using now. 或者,如果您真的喜欢现在使用的结构。

d = {'BTC': [(None, None), (1, -0.4), (3, 0.3333333333333333), (0, 0.75), (1, None)],
 'ETH': [(None, None), (0, 0.5), (0, 0.3333333333333333), (0, -0.1), (2, None)]}

d=pd.DataFrame(d)

Another solution 另一种解决方案

result = []
for key, value in raw.items():
    for index, item in enumerate(value):
        if len(result) <= index:
            result.append({key: item})
        else:
            result[index][key] = item

result

You can use a list comprehension after calculating the number of list elements: 您可以在计算列表元素的数量之后使用列表推导:

d = {'BTC': [(None, None), (1, -0.4), (3, 0.3333333333333333), (0, 0.75), (1, None)],
     'ETH': [(None, None), (0, 0.5), (0, 0.3333333333333333), (0, -0.1), (2, None)]}

n = len(next(iter(d_input.values())))
res = [{k: v[i] for k, v in d_input.items()} for i in range(n)]

If you are able to use 3rd party Pandas, perhaps the easiest way is to convert to a dataframe and then use to_dict : 如果您能够使用第三方熊猫,也许最简单的方法是转换为数据to_dict ,然后使用to_dict

import pandas as pd

res = pd.DataFrame(d_input).to_dict('records')

print(res)

[{'BTC': (None, None), 'ETH': (None, None)},
 {'BTC': (1, -0.4), 'ETH': (0, 0.5)},
 {'BTC': (3, 0.3333333333333333), 'ETH': (0, 0.3333333333333333)},
 {'BTC': (0, 0.75), 'ETH': (0, -0.1)},
 {'BTC': (1, None), 'ETH': (2, None)}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM