将键值对的单个列表项转换为 python 中的字典

Convert a single list item of key value pair to an dictionary in python

我的功能是 returns 只是一个键值对列表。如何将其转换为实际键值或对象类型,以便从列表中获取每个属性。例如,我希望能够只获取时间或价格或任何其他 属性 而不是将整个列表作为一个项目。

{'time': 1512858529643, 'price': '0.00524096', 'origQty': '530.00000000'

我知道它看起来不像列表,但它确实是!我调用的函数 returns this 作为一个列表。我只是将它存储到一个变量中,仅此而已。

open_order=client.get_open_orders(symbol="BNBETH",recvWindow=1234567)

如果您还有疑问。当我尝试打印这样的字典项时 print(open_order['time'])

我收到以下错误。

Traceback (most recent call last): File "C:\Python27\python-binance-master\main.py", line 63, in <module> print(open_order['time']) TypeError: list indices must be integers, not str

此外,如果我显示类型,它会显示为列表。

print(type(open_order))

所以,我想出了一个解决方案,有点...通过将列表转换为字符串并在“,”字符处拆分。现在我有一个项目列表,我可以通过选择一个 print(split_order_items[5]) 来实际打印。必须有更好的解决方案。

open_order=client.get_open_orders(symbol="BNBETH",recvWindow=1234567) y=''.join(str(e)for e in open_order) split_order_items =([x.strip() for x in y.split(',')]) print(split_order_items[5])

我能够使用上面的代码创建多个列表项。我似乎无法将其转换为字典对象!

谢谢!

您发布的是 dict,不是列表。你可以这样做:

data = {'time': 1512858529643, 'price': '0.00524096', 'orderId': 7848174, 'origQty': '530.00000000'}
print(data['time']) # this gets just the time and prints it
print(data['price']) # this gets just the price and prints it

我强烈建议阅读 Python dicthttps://docs.python.org/3/tutorial/datastructures.html#dictionaries