I want to create a Dictionary called \"First\" (as in First Name) that will store numerous first names which are all stored in the dictionary via a function. The idea is th
Python < 2.5 doesn't have defaultdict
, however you can achieve the same thing in with ordinary dict
too.
>>> names = {}
>>> name_list = [('Jon', 'Skeet'), ('Jeff', 'Atwood'), ('Joel', 'Spolsky')]
>>> for first, last in name_list:
names.setdefault('first', []).append(first)
names.setdefault('last', []).append(last)
>>> print names
{'first': ['Jon', 'Jeff', 'Joel'], 'last': ['Skeet', 'Atwood', 'Spolsky']}
setdefault
returns the existing value if the key already exists in dict, or sets the new value and returns the newly set value if the key doesn't exist.