Ali
Ali

Reputation: 33

Filtering out python dictionary based on a key`s values

I have a dictionary dictM in the form of

dictM={movieID:[rating1,rating2,rating3,rating4]}

Key is a movieID and rating1, rating2, rating3, rating4 are its values. There are several movieID's with ratings. I want to move certain movieID's along with ratings to a new dicitonary if a movieID has a certain number of ratings.

What I'm doing is :

for movie in dictM.keys():
    if len(dictM[movie])>=5:
        dF[movie]=d[movie]

But I'm not getting the desired result. Does someone know a solution for this?

Upvotes: 2

Views: 74

Answers (3)

MSeifert
MSeifert

Reputation: 152860

You don't delete the entries, you could do it like this:

dictM = {1: [1, 2, 3],
         2: [1, 2, 3, 4, 5],
         3: [1, 2, 3, 4, 5, 6, 7],
         4: [1]}

dF = {}
for movieID in list(dictM):
    if len(dictM[movieID]) >= 5:
        dF[movieID] = dictM[movieID]  # put the movie + rating in the new dict
        del dictM[movieID]            # remove the movie from the old dict

The result looks like this:

>>> dictM
{1: [1, 2, 3], 4: [1]}
>>> dF
{2: [1, 2, 3, 4, 5], 3: [1, 2, 3, 4, 5, 6, 7]}

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71471

You can try this using simple dictionary comprhension:

dictM={3:[4, 3, 2, 5, 1]}

new_dict = {a:b for a, b in dictM.items() if len(b) >= 5}

One reason why your code above may not be producing any results is first, you have not defined dF and the the length of the only value in dictM is equal to 4, but you want 5 or above, as shown in the if statement in your code.

Upvotes: 1

Ami Tavory
Ami Tavory

Reputation: 76381

You can use dictionary comprehension, as follows:

>>> dictM = {1: [1, 2, 3, 4], 2: [1, 2, 3]}

>>> {k: v for (k, v) in dictM.items() if len(v) ==4}
{1: [1, 2, 3, 4]}

Upvotes: 1

Related Questions