0

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

2
  • [item[2] for item in d.values()] (you shouldn't use dict as a variable name...it overwrites the builtin dict). Commented Feb 10, 2022 at 20:59
  • Thanks for this! I'll try to keep from using dict from now on. Commented Feb 10, 2022 at 21:10

3 Answers 3

1

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'] 
Sign up to request clarification or add additional context in comments.

1 Comment

THANKS! This worked
0

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 

1 Comment

Thanks! I like the option of printing both the key and item
0

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

Comments