繁体   English   中英

如何打印字典中的多个项目

[英]How to print multiple items in a dictionary

这个问题似乎是一个愚蠢的问题,因为它非常基础,但我真的很挣扎。 我有一个不断更新的来自 python-binance 网络套接字的数据流,这是市场中当前货币的价格。 我试图将使用该行时出现的符号和价格分开:

info = client.get_all_tickers()

它打印以下内容,这将是输出的一部分:

[{'symbol': 'ETHBTC', 'price': '0.06327900'}, {'symbol': 'LTCBTC', 'price': '0.00406800'}, ...]

我的目标是隔离符号和价格,并将它们打印在一起,而不是使用短语“符号”和“价格”,这样我就可以完成价格的数学方程,因此我还可以输出两个值一种美化的方式。

到目前为止我已经尝试过这个:

symbolGetter = [ swap['symbol'] for swap in info ]

获取我的符号和:

priceGetter = [ swap['price'] for swap in info ]

这只会将它们分开,但尝试使用这些我认为可行的方法将它们彼此相邻打印:

symbolAndPriceGetter = [ swap['symbol', 'price'] for swap in info ]
print(symbolAndPriceGetter)

这给我带来了错误:

KeyError: ('symbol', 'price')

尝试另一种方式:

symbolGetter = [ swap['symbol', 'price'] for swap in info ]
priceGetter = [ swap['price'] for swap in info ]
print(symbolGetter, priceGetter)

返回打印在一个列表中的符号,然后返回打印在另一个列表中的价格。

我怎么能回去(符号,价格)(符号,价格)...

感谢您的任何帮助

您可以将每个项目格式化为这样的字符串:

stringified = ['{0} {1}'.format(swap["symbol"], swap["price"]) for swap in info]

然后你可以打印它们中的每一个:

for s in stringified:
    print(s)

或者在单个操作中:

print('\n'.join(stringified))

两者都会导致:

ETHBTC 0.06327900
LTCBTC 0.00406800

另一方面,如果您想将其写入 csv,则可以为此使用csv.DictWriter

with open('swaps.csv', 'w', newline='') as csvfile:
    fieldnames = ['symbol', 'price']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerows(info)

试试这个:

for a in info:
    print(list(a.values()))

你会得到:

['ETHBTC', '0.06327900']
['LTCBTC', '0.00406800']

另一种解决方案是:

for a in info:
    print(*a.values())

你会得到:

ETHBTC 0.06327900
LTCBTC 0.00406800
from decimal import Decimal

dl = [{'symbol': 'ETHBTC', 'price': '0.06327900'}, {'symbol': 'LTCBTC', 'price': '0.00406800'}]

res = [(d['symbol'], Decimal(d['price'])) for d in dl]
print(res)
# [('ETHBTC', Decimal('0.06327900')), ('LTCBTC', Decimal('0.00406800'))]

# Then for example if you want aveage of price
prices = [t[1] for t in res]
ave_price = sum(prices) / (len(prices))
print(ave_price)
# 0.03367350

您可以将表达式放入列表推导式中,例如:

prices_as_tuples = [ (swap['symbol'], swap['price']) for swap in info ]

或者,将其格式化为文本

prices_for_printing = [ "%s at %s" % (swap['symbol'], swap['price']) for swap in info ]

print("; ".join(prices_for_printing))

您可以遍历每个字典的值并使用生成器打印它们

print(*(' '.join(v for v in d.values()) for d in info), sep='\n')

# ETHBTC 0.06327900
# LTCBTC 0.00406800

暂无
暂无

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

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