Warm tip: This article is reproduced from stackoverflow.com, please click
dictionary python

Python updating a dictionary based on most occurred item

发布于 2020-03-27 15:40:01

I have a list of webpages for example

pages = [login, ask, profile, search]

I am busy iterating through a different list of users, each can visit any webpage several times. I need to know who the top visitor for each page is. I want to use dictionaries because of its functionality.

This is hard to explain, because I have many many nested structures in my code. To simplify I will both word the problem, and try and illustrate.

PROBLEM:

When iterating through a user, another nested iteration IS a webpage that the user visited.

users = ['tom', 'jerry', 'dexter', 'deedee', 'buttercup']

for user in users:
   for session in sessions:
      for page in activities:
            webpage = user_visited  # this can be any of the pages mentioned earlier

I need to find a way to see for each webpage which user visited it most

EXPECTING something like this:

{ login: dexter, ask: jerry, profile: buttercup, search: tom}

I am open to any method, please help

Questioner
Llewellyn Hattingh
Viewed
43
jignatius 2020-02-01 00:14

I would maintain a dictionary of webpages and users like this:

d = {'login' : {'tom':1, 'jerry':0, 'dexter':2, 'deedee':3, 'buttercup':1},
     'ask' : {'tom':0, 'jerry':0, 'dexter':3, 'deedee':2, 'buttercup':1},
     'profile': {'tom':4, 'jerry':2, 'dexter':2, 'deedee':3, 'buttercup':1},
     'search': {'tom':1, 'jerry':0, 'dexter':2, 'deedee':0, 'buttercup':4},
}

where the key is the webpage and the value is a dictionary of users and webpage visits. Increment the count inside the dictionary of each page when a user visits. Then its simple to get the most frequent visitor to each page:

from collections import Counter

l = []
for key,dd in d.items():
    c = Counter(dd)
    l.append({key : c.most_common(1)[0]})
print(l)

Output:

[{'login': ('deedee', 3)}, {'ask': ('dexter', 3)}, {'profile': ('tom', 4)}, {'search': ('buttercup', 4)}]

Update:

To create your dictionary d you firstly need a list of pages and users:

pages = ['login', 'ask', 'profile', 'search']
users = ['tom', 'jerry', 'dexter', 'deedee', 'buttercup']

You can then create your dictionary using dictionary comprehension:

d = {page: {user: 0 for user in users} for page in pages}

There are two for loop here - one to iterate the pages and another the users for each page. You will then get a structure like this:

{'login': {'tom': 0, 'jerry': 0, 'dexter': 0, 'deedee': 0, 'buttercup': 0},
 'ask': {'tom': 0, 'jerry': 0, 'dexter': 0, 'deedee': 0, 'buttercup': 0},
 'profile': {'tom': 0, 'jerry': 0, 'dexter': 0, 'deedee': 0, 'buttercup': 0},
 'search': {'tom': 0, 'jerry': 0, 'dexter': 0, 'deedee': 0, 'buttercup': 0}}

After that it is quite simple to update the web page visit for each user:

d['login']['tom'] += 1