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
Turn data['Names']['first']
in a list and append to it:
data['Names'] = {}
data['Names']['first'] = []
def store(data, value):
data['Names']['first'].append(value)
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.
You should probably be storing the list of names as a list, rather than a dictionary. So you would have:
data['Names'] = {}
data['Names']['first'] = [] #note the brackets here instead of curlies
data['Names']['first'] = [value1, value2]
To add one after instantiation, you can do:
data['Names']['first'].append(another_first_name)
Lists are zero-indexed, so to get the 1st first name, you can say:
data['Names']['first'][0]
Have a look at collections.defaultdict. Then you can do things like:
from collections import defaultdict
data['Names'] = defaultdict(list) # Or pass set instead of list.
data['Names']['first'].append("Bob")
data['Names']['first'].append("Jane")
data['Names']['last'].extend("T", "Mart")