简体   繁体   中英

Python printing values of values in a dictionary

In Python, I know you print the values of a key in a dictionary by doing variable.values() . But what if I wanted to print a value of a particular value?

For an example:

pets = {'Dog': ['Poodle', 'Boxer', 'Terrier'], 'Cat': ['Sphynx', 'Ragdoll', 'Birman']}

I want to specifically choose a particular breed of animal. For instance, I just want to print Boxer .

You could do something like:

animal = list(pets.values())[0]
breed = list(animal.values())[1]
print(breed)

This will give you Boxer . However, I was curious if I can do this in a single line of code like printing a value of a value.

I've tried:

breed = list(list(pets.values()))[0][1]

but it tells me that the string index is out of range.

print(list(pets.values()))

output:

[['Poodle', 'Boxer', 'Terrier'], ['Sphynx', 'Ragdoll', 'Birman']]
  • As you can see its a list of list. Now each item is list you can access by indexing.
breed = list(pets.values())[0][1]
  • this will give you desired result.

your data structure is a dict with "sets" as values. sets are not subscriptable and converting in a list doesn't keep the order

>>> list(pets['Dog'])
['Boxer', 'Poodle', 'Terrier']

the question is then.... what do you really need?

If you need to access to breed you could/should use lists or tuples instead of sets

it seems strange about how you are using dict, I assume in your case you should use list instead

pets = {'Animal': {'Dog': ['Poodle', 'Boxer', 'Terrier'], 'Cat': ['Sphynx', 'Ragdoll', 'Birman']}}

if you want a specific breed to print, then you might need an additional key for that to gain benefits of using dict

pets = {'Animal': {'Dog': {1:'Poodle', 2:'Boxer', 3:'Terrier'}, 'Cat': ['Sphynx', 'Ragdoll', 'Birman']}}

then you can get boxer with

pets['Animal']['Dog'][2]

The way you are defining this dictionary creates a syntax error:

>>> pets = {'Animal': 'Dog':{'Poodle','Boxer','Terrier'}, 'Cat':{'Sphynx','Ragdoll','Birman'}}
  File "<stdin>", line 1
    pets = {'Animal': 'Dog':{'Poodle','Boxer','Terrier'}, 'Cat':{'Sphynx','Ragdoll','Birman'}}
                           ^
SyntaxError: invalid syntax

I created a similar dictionary (this time a dictionary of species as key and breeds as values), and show how you can index this new dictionary:

>>> pets = {'Dog':('Poodle','Boxer','Terrier'), 'Cat':('Sphynx','Ragdoll','Birman')}
>>> pets['Dog'][1]
'Boxer'
>>>

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