从字典中的选定项目中打印键值

时间:2018-10-05 05:21:36

标签: python dictionary

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

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

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

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

我收到此错误代码:

TypeError: 'int' object is not callable

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

3 个答案:

答案 0 :(得分:1)

您的selecteditem是值45,然后尝试遍历selecteditem,但这只是一个整数,因此出现错误:

for k, v in inventoryitems.items():
    print(k, v)

答案 1 :(得分:1)

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

答案 2 :(得分:0)

由于您已经拥有密钥weapon1,因此您实际上只需要一个值,因为您已经为其分配了selectedItem,所以该值已经存储在inventoryitems["weapon1"]中。这里不需要任何进一步的调用或迭代。