In [1]:
birthdays = {'Newton' : 1642, 'Darwin' : 1809}
Key | Value |
---|---|
'Newton' | 1642 |
'Darwin' | 1809 |
In [2]:
print birthdays['Newton']
In [3]:
birthdays['Turing'] = 1612
print birthdays
In [4]:
birthdays['Turing'] = 1912
print birthdays
In [5]:
print birthdays['Nightingale']
in
In [6]:
print 'Nightingale' in birthdays
In [7]:
print 'Darwin' in birthdays
len
reports the number of items in the dictionaryfor
loops over the keys in some arbitrary order
In [8]:
print len(birthdays)
for name in birthdays:
print name, birthdays[name]
In [14]:
def main(filename):
counts = count_atoms(filename)
for atom in counts:
print atom, counts[atom]
In [15]:
def count_atoms(filename):
'''Count unique atoms, returning a dictionary.'''
result = {}
with open(filename, 'r') as reader:
for line in reader:
atom = line.strip()
if atom not in result:
result[atom] = 1
else:
result[atom] = result[atom] + 1
return result
In [16]:
main('some_atoms.txt')
In [17]:
birthdays = {
('Isaac', 'Newton') : 1642,
('Charles', 'Robert', 'Darwin') : 1809,
('Alan', 'Mathison', 'Turing') : 1912
}
print birthdays
keys
and values
methods to get lists of keys and values
In [18]:
all_keys = birthdays.keys()
print all_keys
In [20]:
all_values = birthdays.values()
print all_values
dict.keys()
, since that creates a list of keys rather than using them directly{k1:v1, k2:v2, ...}
.dict[key]
refers to the dictionary entry with a particular key.key in dict
tests whether a key is in a dictionary.len(dict)
returns the number of entries in a dictionary.dict.keys()
creates a list of the keys in a dictionary.dict.values()
creates a list of the keys in a dictionary.