python - Iterate and compare first item to all items in dictionary -


please help, can't seem find way this. working on web science project , third project python.

i need compare first item in dictionary other items in same dictionary, other items dictionaries.

for example, have dictionary has following values:

{'25': {'return of jedi (1983)': 5.0},  '42': {'batman (1989)': 3.0, 'e.t. extra-terrestrial (1982)': 5.0},  '8': {'return of jedi (1983)': 5.0 },'542': {'alice in wonderland (1951)': 3.0, 'blade runner (1982)': 4.0}, '7': {'alice in wonderland (1951)': 3.0,'blade runner (1982)': 4.0}}  

so need see if keys '25' , '42' contain same movie "return of jedi" in case, if '25' , '8' have same movie , on. do, need know how many movies overlap.

this example of dictionary, whole dictionary contains 1000 keys , sub-dictionaries way bigger also.

i tried iterate, compare dictionaries, make copies, merge, join, can´t seem grasp how can this.

help please!

the thing still can't compare both subdictionaries because need find keys have @ least 2 of same movies whole.

you can use collections.counter:

>>> dic={'25': {'return of jedi (1983)': 5.0}, '42': {'batman (1989)': 3.0, 'e.t. extra-terrestrial (1982)': 5.0}, '8': {'return of jedi (1983)': 5.0 }} >>> collections import counter >>> c=counter(movie  v in dic.values() movie in v)  >>> [k k,v in c.items() if v>1] #returns name of movies repeated more once ['return of jedi (1983)'] >>> c counter({'return of jedi (1983)': 2,          'batman (1989)': 1,          'e.t. extra-terrestrial (1982)': 1}) 

to keys related each movie can use collections.defaultdict:

>>> collections import defaultdict >>> movie_keys=defaultdict(list) >>> k,v in dic.items():      movie in v:         movie_keys[movie].append(k) ...          >>> movie_keys defaultdict(<type 'list'>, {'batman (1989)': ['42'], 'return of jedi (1983)': ['25', '8'], 'e.t. extra-terrestrial (1982)': ['42']}) 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -