Ziva
Ziva

Reputation: 3521

Assign many values to an element of a list

If I want to assign to an element of a list only one value I use always a dictionary. For example:

{'Monday':1, 'Tuesday':2,...'Friday':5,..}

But I want to assign to one element of a list many values, like for example:

Monday: Jogging, Swimming, Skating
Tuesday: School, Work, Dinner, Cinema
...
Friday: Doctor

Is any built-in structure or a simple way to make something like this in python? My idea: I was thinking about something like: a dictionary which as a key holds a day and as a value holds a list, but maybe there is a better solution.

Upvotes: 0

Views: 59

Answers (1)

abarnert
abarnert

Reputation: 366123

A dictionary whose values are lists is perfectly fine, and in fact very common.

In fact, you might want to consider an extension to that: a collections.defaultdict(list). This will create a new empty list the first time you access any key, so you can write code like this:

d[day].append(activity)

… instead of this:

if not day in d:
    d[day] = []
d[day].append(activity)

The down-side of a defaultdict is that you no longer have a way to detect that a key is missing in your lookup code, because it will automatically create a new one. If that matters, use a regular dict together with the setdefault method:

d.setdefault(day, []).append(activity)

You could wrap either of these solutions up in a "MultiDict" class that encapsulates the fact that it's a dictionary of lists, but the dictionary-of-lists idea is such a common idiom that it really isn't necessary to hide it.

Upvotes: 2

Related Questions