简体   繁体   中英

How to print a list of keys from a dictionary with a specific

At the moment I'm currently trying to check a dictionary of items and go through them checking for a value. If the value is more than 0 then it prints it in a list, otherwise its ignored and it goes on. Currently I have this code typed out :

from items import items

for item in items:
    if items[item][6] < 0:
        print("You have ", item[6], " of ", item[0], " .")

But from here I'm pretty confused as to how to continue with this. I'm getting an index error but I'm not sure what its for.

You are iterating over a dictionary where the key is the item's name and the value is a tuple with some information in it.

You could do it like this Note this will only work if your tuple ALWAYS has the same structure / number of fields.

In [23]: my_items = {'Broken Watch': ('Broken Watch', 'This is a watch. It appears to be shattered, and the hands are no longer moving.', 'Item', 'Junk', 1, 1, 0), 'Watch that will
    ...:  print': ('Some stuff', 'More stuff', 'Item', 'Junk', 1, 1, 7)}                                                                                                            

In [24]: for name, info in my_items.items(): 
    ...:     num= info[6] 
    ...:     print("Checking num", num) 
    ...:     if num > 0: 
    ...:         print("You have", num, "of", name, ".") 
    ...:          
    ...:          
    ...:                                                                                                                                                                            
Checking num 0
Checking num 7
You have 7 of Watch that will print .

You aren't subscripting item properly. item is a key in items , and you have to relate to it as such (like you did in the if statement). Note, also, that according to the question's text, you probably meant to use the > operator, not < :

for item in items:
    if items[item][6] > 0: 
        print("You have ", items[item][6], " of ", items[item][0], " .")

As a side note, all the values you need seem to be in the value tuple, so you could just iterate over the values instead of the using the keys to access them:

for item in items.values():
    if item[6] > 0: 
        print("You have ", item[6], " of ", item[0], " .")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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