开发者

Method to Find Out When Users Cancelled Using Dictionaries

I have created a dictionary of either {'username': 'date'} or {'date': 'username'} (I can change the order of the key: value pair to whichever I want). To set the values I need to say...

{'Jacob Rasnip': 'Apr', 'Andrew Alexander': 'Apr', 'Jacob Rasnip': 'May'}

or the opposite...

{'Apr': 'Jacob Rasnip'}

I have about 1500 of dictionary values, all users with different months assigned to them or months assigned with users.

I want a way to iterate through a dictionary of keys and values, and figure out which month was the first month a customer appeared. I also want to find the last month that the customer appeared.

Could someone please offer开发者_如何学编程 advice as to the best way to achieve this.


A dictionary cannot have duplicate keys. For example, it can only have one key 'Jacob Rasnip'. Your example shows two. Similarly, a dictionary could only have one key 'Apr'.

If instead you had dictonary of usernames mapping to a list of datetime.dates:

{'Jacob Rasnip': [datetime.date(2011,4,1),datetime.date(2011,5,1),]...}

Then you could generate the first and last months with

for user,dates in user_dict.iteritems():
    first_date = min(dates)
    last_date = max(dates)
    print(user,first_date,last_date)

Note min and max rely on the items in dates being datetime.date objects. It would also work with simple integers representing the months (assuming all months refer to the same year). But it would not work as desired with string names for the months (e.g. 'Apr').


You said.

Could I have each name (as a key) have multiple values? Currently I'm combining two lists (one of names, the other of dates) like this: testdict = dict(zip(name, date))

No, but you can combine those values in a way that looks like unutbu's answer.

import collections
data = collections.defaultdict(list)

for n, d in zip(name, date):
    data[n].append(d)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜