简体   繁体   中英

Accessing elements in Python dictionary

bit of a strange question, but I was trying to come up with different ways to get around this.

Let's say I have the following Dictionary:

dict={

    'Animal':['Cat', 'Dog', 'Ocelot'],
    'Humans':['Jack', 'Jill', 'Frank'], 
    'Fruit':['Apple', 'Orange', 'Banana']
}

Is there a way to access just the third element of every key? The output being 'Ocelot' 'Frank 'Banana'

I know that the notation for single key is Dictionary(KEY)[ITEM PLACE] but is there a way to do this without specifying the key?

Thanks

Here's one approach.

d = {
    'Animal':['Cat', 'Dog', 'Ocelot'],
    'Humans':['Jack', 'Jill', 'Frank'], 
    'Fruit':['Apple', 'Orange', 'Banana']
}
print([d[k][2] for k in d])

Result:

['Ocelot', 'Frank', 'Banana']

You can access the values without using a key;

>>> d = {'Animal': ['Cat', 'Dog', 'Ocelot'],
...  'Humans': ['Jack', 'Jill', 'Frank'],
...  'Fruit': ['Apple', 'Orange', 'Banana']}
>>> 
>>> d.values()
dict_values([['Cat', 'Dog', 'Ocelot'], ['Jack', 'Jill', 'Frank'], ['Apple', 'Orange', 'Banana']])
>>> [i[2] for i in d.values()]
['Ocelot', 'Frank', 'Banana']

Often it is more useful to iterate over the items:

>>> for k, v in d.items():
...     print(k, v[2])
... 
Animal Ocelot
Humans Frank
Fruit Banana

We could do this in one line if needed:

list(map(lambda x:x[2], dict.values()))
>>> dict={
...
...     'Animal':['Cat', 'Dog', 'Ocelot'],
...     'Humans':['Jack', 'Jill', 'Frank'],
...     'Fruit':['Apple', 'Orange', 'Banana']
... }
>>> dict
{'Animal': ['Cat', 'Dog', 'Ocelot'], 'Humans': ['Jack', 'Jill', 'Frank'], 'Fruit': ['Apple', 'Orange', 'Banana']}
>>> list(map(lambda x:x[2], dict.values()))
['Ocelot', 'Frank', 'Banana']

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