tad
tad

Reputation: 41

Accessing nth Element of a list value for a given key: Python dictionary

I have a dictionary as follows:

d = {key: [val1, val2, val3....], key2: [valx, valy, valz, ...], ....}

Is it possible to get nth element of the value lists? Example: d{key2:[2]} would return 'valz'.

I tried d.get({key:[0]}) but got:

"TypeError: unhashable type: 'dict'"

Upvotes: 3

Views: 6422

Answers (3)

pppery
pppery

Reputation: 3814

Your problem is that d.get({key:[0]}) is equivanlent to d[{key:[0]}], amd dictionaries are illegal keys in dictionaries. The correct solution is d[key][0]

Upvotes: 0

John Perry
John Perry

Reputation: 2678

d[key][0] does the trick for me, unless I misunderstand the question.

Upvotes: 5

cdonts
cdonts

Reputation: 9631

To get valz just use d[key2][2].

Upvotes: 1

Related Questions