Home > Software engineering >  Accessing elements in Python dictionary
Accessing elements in Python dictionary

Time:02-11

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

CodePudding user response:

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']

CodePudding user response:

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

CodePudding user response:

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']
  • Related