python - 打印字典中所选项目的键值

标签 python dictionary

我想从字典中找到 Weapon1,然后打印它的“键”和“值”对,以便我可以单独引用它们。这适用于字典中的所有项目,但当我只想要一个项目时,我似乎无法使其工作。

inventoryitems = {"weapon1": 45, "weapon2": 5}

selecteditem = inventoryitems["weapon1"]
print(selecteditem)

for k, v in selecteditem():
    print(k, v)

我收到此错误代码:

TypeError: 'int' object is not callable

到目前为止,我了解它调用 Wea​​pon1 的值(即“int”),但我想从字典中找到的项目中调用键和值。对此的任何帮助将不胜感激!

最佳答案

inventoryitems = {"weapon1": 45, "weapon2": 5}

selecteditem = inventoryitems["weapon1"]
# by doing this you have assigned the value of key( = weapon1) to the variable selecteditem
# since this value was int now your selecteditem is int

print(selecteditem) # will print 45

# but now you are try to call selecteditem which is an int, and you can't call an int so python will give you an error

'''
for k, v in selecteditem():
    print(k, v)

'''


# instead do this 

selecteditem, selecteditem_value = 'weapon1', inventoryitems["weapon1"]

print('you selected {0} and its power is {1}'.format(selecteditem, selecteditem_value)) #you selected weapon1 and its power is 45


编辑:

inventoryitems = {"weapon1": 45, "weapon2": 5}

def user_selection( item_selected):
    print('you selected {0} and its power is {1}'.format(item_selected, inventoryitems[item_selected])) #you selected weapon1 and its power is 45


user_selection( 'weapon1') # you selected weapon1 and its power is 45

关于python - 打印字典中所选项目的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52658795/

相关文章:

python - 在子图中写入文本

python - 负数的模数

Python,BeautifulSoup,重新: How to convert extracted texts to dictionary from web?

c# - 循环遍历两个并发字典的 Lambda 表达式

python - 空值和排序

python - 如何处理 Linux/Python 依赖?

python - 在 numpy 中矢量化 VLAD 计算

python - 不使用递归的字典中键值对的最长循环

python - 如何返回字典中某个值的频率列表

ios - TableViewCell 问题上的 MapView