简体   繁体   中英

Python 3 - Print Specific List Item from Dictionary

I have a dictionary with lists attached to the keys with multiple values inside each list. I'm trying to pull a specific item from the lists of each key. I assumed I could do the following;

for entries in myDictionary:
    print("Customer :" + entries[1])
    print("Sales Rep:" + entries[2])
    print("Item: " + entries[3])

Though that only prints the second, third, and fourth characters of what I assume to be the key itself - it could also be the first list item as I also have the key as the first item within the lists, but I'm going to assume it's the former.

I've read about the following, but I'm unsure how to apply it to my case of wanting to print a specific item from the list. I believe these would print out the entire list per key;

for key, value in my_dict.iteritems():
    print key, value
for key in my_dict.iterkeys():
    print key
for value in my_dict.itervalues():
    print value

Cheers.

Iterating over the dictionary gives you keys ; you can always use that key to access the value:

for key in myDictionary:
    entries = myDictionary[key]
    print("Customer:", entries[1])
    print("Sales Rep:", entries[2])
    print("Item:", entries[3])

Using dict.values() (or dict.itervalues() or dict.viewvalues() when using Python 2) gives you access to the values instead, which you can then index:

for entries in myDictionary.values():
    print("Customer:", entries[1])
    print("Sales Rep:", entries[2])
    print("Item:", entries[3])

or you can have both the keys and the values with dict.items() ( dict.iteritems() , dict.viewitems() ):

for key, entries in myDictionary.items():
    print("Details for:", key)
    print("Customer:", entries[1])
    print("Sales Rep:", entries[2])
    print("Item:", entries[3])

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