Python-Ref > Data structures > Dictionaries > Building dictionary from input data
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Building dictionary from input data

In real world you usually don't have a dictionary available for use and you have to create it from source data. The following example shows the typical approach to creating a dictionary from input data.
Expand/Shrink
Programmer,20000
Boss,100000
Assistant,20000
Cleaning staff,9000
IT manager,50000
Director,150000
Zdroj: (dict4-1.py)
  1   inp = file( "salaries.csv", "r")
  2   name2money = {}
  3   
  4   for line in inp:
  5     if line.strip():  # the line is non-empty
  6       name, money = line.strip().split(",")
  7       name2money[ name] = int( money)
  8   
  9   print name2money
 10   print "mean salary:", sum( name2money.values()) / len( name2money)
stdout:
{'IT manager': 50000, 'Cleaning staff': 9000, 'Assistant': 20000, 'Boss': 100000, 'Director': 150000, 'Programmer': 20000}
mean salary: 58166
Doba běhu: 31.6 ms
The previous example presented a way to deal with one-to-one relationships between data. However very often there is the need to associate more values with one key. In this case we need to store all the possible values in a list. The following code demonstrates this approach.
Expand/Shrink
Zdroj: (dict4-3.py)
  1   names = ["Jane","John","David","Paul","Peter","Amy","Steve","Lucy","Anne"]
  2   
  3   first_letter2name = {}
  4   for name in names:
  5     first_letter = name[0]
  6     if first_letter in first_letter2name:
  7       # the letter is already present in the dictionary
  8       first_letter2name[ first_letter].append( name)
  9     else:
 10       first_letter2name[ first_letter] = [name]
 11   
 12   print first_letter2name
 13   keys = first_letter2name.keys()
 14   for key in keys:
 15     print key, first_letter2name[ key]
stdout:
{'A': ['Amy', 'Anne'], 'D': ['David'], 'J': ['Jane', 'John'], 'L': ['Lucy'], 'P': ['Paul', 'Peter'], 'S': ['Steve']}
A ['Amy', 'Anne']
D ['David']
J ['Jane', 'John']
L ['Lucy']
P ['Paul', 'Peter']
S ['Steve']
Doba běhu: 20.3 ms
Expand/Shrink
Zdroj: (dict4-2.py)
  1   names = ["Jane","John","David","Paul","Peter","Amy","Steve","Lucy","Anne"]
  2   
  3   first_letter2name = {}
  4   for name in names:
  5     first_letter = name[0]
  6     if first_letter not in first_letter2name:
  7       # the letter is already present in the dictionary
  8       first_letter2name[ first_letter] = []
  9     first_letter2name[ first_letter].append( name)
 10   
 11   print first_letter2name
 12   keys = first_letter2name.keys()
 13   for key in keys:
 14     print key, first_letter2name[ key]
stdout:
{'A': ['Amy', 'Anne'], 'D': ['David'], 'J': ['Jane', 'John'], 'L': ['Lucy'], 'P': ['Paul', 'Peter'], 'S': ['Steve']}
A ['Amy', 'Anne']
D ['David']
J ['Jane', 'John']
L ['Lucy']
P ['Paul', 'Peter']
S ['Steve']
Doba běhu: 58.3 ms