Python's solution to the problem of lists of values in dictionaries

  • 2020-04-02 09:53:19
  • OfStack

Problem: where to find some English words is small sentences appeared, is implemented in python, of course, is to use a dictionary, of course, but how to make a list of key corresponding to a type of value, directly in the list of append () are not enough, such as dic [key]. Append (value), because of the type of the interpreter does not know dic [key], was in a hurry, took a compromise solution, is to use the value into a STR, with STR. Finally the split () to make a transformation, to generate a list.

      Check out the python cookbook, which has a recipe for how to handle such a problem.

(1) duplicate items are allowed in value.


dic = {}
dic.setdefault(key . []).append(value)
# Such as :
d1.setdefault('bob_hu' . []).append(1)
d1.setdefault('bob_hu' . []).append(2)
print d1['bob_hu'] # [1 . 2]

(2) there is no duplicate item in value.


dic = {}
dic.setdefault(key . {})[value] = 1
# Such as :
d1.setdefault('bob' . {})['f'] = 1
d1.setdefault('bob' . {})['h'] = 1
d1.setdefault('bob' . {})['f'] = 1
print d1['bob'] #{'h': 1 .  'f': 1}


Related articles: