Python-打印Di中的键字符串

2024-04-29 03:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下

prices = {'banana':'4', 'apple':'2', 'orange':'1.5', 'pear':'3'}
stock = {'banana':6, 'apple':0, 'orange':32, 'pear':15}

print(prices.keys)
print("price :" + str(prices.values))
print("stock :" + str(stock.values))

我不明白为什么我会被吐出来,看起来像是我要求的类型。给什么?

实际上,我的代码逻辑是错误的。

我想让代码说出以下内容

钥匙 价格:价值 股票:价值

例如,它应该是这样的

苹果 价格:2 库存:0


Tags: 代码applestock价格keyspricebananaprices
3条回答

您需要调用这些方法以获取任何有用的信息:

print (prices.keys())

然而,在python3.x中,这仍然不太适合打印,因为它会打印出您可能不想看到的额外垃圾。

您可能需要考虑对从dict.keys()dict.values()返回的对象使用str.join

print (' '.join(prices.keys()))

str.join做了很多你想做的事情。左边的字符串是在传递给join的iterable中的每个元素之间插入的分隔符。例如:

"!".join(["foo","bar","baz"])

将生成字符串:"foo!bar!baz"。这里唯一的问题是,传递给str.join的iterable中的每个元素都必须是一个字符串。


至于你的编辑

prices = {'banana':'4', 'apple':'2', 'orange':'1.5', 'pear':'3'}
stock = {'banana':6, 'apple':0, 'orange':32, 'pear':15}
prices.keys() & stock.keys()  #{'orange', 'pear', 'banana', 'apple'}
for item in (prices.keys() & stock.keys()):
    print (item,"price:",prices[item],"stock:",stock[item])

哪些输出:

orange price: 1.5 stock: 32
pear price: 3 stock: 15
banana price: 4 stock: 6
apple price: 2 stock: 0

好像这就是你想要的。

prices = {'banana':'4', 'apple':'2', 'pear':'3'}
stock = {'banana':6, 'orange':32, 'pear':15}
for item in (prices.keys() & stock.keys()):
    print (item,"price:",prices.get(item,'-'),"stock:",stock.get(item,0))

产生

orange price: - stock: 32
pear price: 3 stock: 15
banana price: 4 stock: 6
apple price: 2 stock: 0

如果stock和prices字典在每个字典中包含不同的薯条('keys'),那么使用默认的get会有帮助。.get()函数在这里确实有帮助。

正如mgilson所提到的,下面一行是创建全套水果的地方。

prices.keys() & stock.keys()  #{'orange', 'pear', 'banana', 'apple'}

我以前也用过set

set(prices.keys().extend(stock.keys())

但我更喜欢&方法。

前两个答案建议使用.keys(),但是note that这将返回类型为dict_keys的对象,而不是像字符串列表那样的可索引对象。要将键的列表作为字符串获取,只需将字典转换为列表:list(my_dict)

>>> prices = {'banana':'4', 'apple':'2', 'pear':'3'}
>>> print(prices.keys())
dict_keys(['banana', 'apple', 'pear'])
>>> prices.keys()[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict_keys' object does not support indexing
>>> print(list(prices))
['banana', 'apple', 'pear']
>>> list(prices)[2]
'pear'

相关问题 更多 >