user2904796
user2904796

Reputation: 267

Key Error with Dictionary

I am having some problems with key errors with my dictionary.

    result={}    
    for (k,v) in movies.items():
        if not v[1] in result:
            result[v[0]]=0
        result[v[0]]+=int(1)
        if not v[2] in result:
            result[v[2]]=0
        result[v[2]]+=int(1)
        if not v[3] in result:
            result[v[3]]=0
        result[v[3]]+=int(1)
        if not v[4] in result:
            result[v[4]]=0
        result[v[4]]+=int(1)
        if not v[5] in result:
            result[v[5]]=0
        result[v[5]]+=int(1)
    list5= sorted(result.items(),key=operator.itemgetter(1),reverse=True)
    print list5

So I am trying to create a dictionary where I loop through another dictionary(movies), and add the actors in each of these movies as my keys. The keys in my dictionary are the names of the actors, and the value will be the number of movies he did in total. However I seem to be getting a key error. Any idea why that might be?

P.S- there are 5 actors in each movie, which is why I have 5 keys for the loop.

Thanks, Junaid

Upvotes: 1

Views: 1477

Answers (3)

John La Rooy
John La Rooy

Reputation: 304137

Much easier to just use a Counter here. As a bonus it doesn't matter anymore how many actors the movie has.

from collections import Counter
c = Counter(i for v in movies.values() for i in v)
print c.most_common()

Another way to loop over the actors is to use chain.from_iterable

from itertools import chain
c = Counter(chain.from_iterable(movies.values()))
print c.most_common()

Upvotes: 3

JRajan
JRajan

Reputation: 702

I think this should be enough for you.

result = {}

for movie, actor_list in movies.iteritems():
    for actor in actor_list:
        result[actor] = result.get(actor, 0) + 1

print sorted(result.items(), key=operator.itemgetter(1), reverse=True)

Upvotes: 1

latheiere
latheiere

Reputation: 451

probably a typo somewhere here:

if not v[1] in result:
    result[v[0]]=0
result[v[0]]+=int(1)

use defaultdict or setdefault for simplicity, and iterate over slice for unification:

 import collections
 result = collections.defaultdict(int)
 for k, values in movies.items():
    for value in values[:6]: # first 6, from 0th to 5th
        result[v] += 1

Upvotes: 1

Related Questions