user1893110 user1893110 - 23 days ago 7
Python Question

Accessing tuple values in a dict

q = "cats dogs"

d = {'cats': {1: 1, 2: 3, 3: 1, 4: 1}, 'nuts': {3: 1}, 'egg': {5: 1, 6: 2}, 'dogs': {1: 8, 2: 2, 3: 4}, 'idea': {4: 1}, 'frog': {2: 1, 4: 1, 5: 1}}

newList = []

for word in q:
for x,y in d.values():
newList.append(d[word].x())


What I'm attempting to do here is get each first part of the number pairs and put into the list when it corresponds to a word in q. So I'm expecting newList to be [1,2,3,4,1,2,3].

I am getting ValueError: too many values to unpack (expected 2). How should I be doing this?

Answer

The values in the dictionary 'd' are actually of type dictionary themselves, not tuples. I think you may want to reorganize this a bit.

for word in q.split(" "):
  if word in d:
    child_dict = d[word]
    for key in child_dict:
      newList.append(key)