我想从字典中找到 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
到目前为止,我了解它调用 Weapon1 的值(即“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/