Assign strings to IDs in Python -


i reading text file python, formatted values in each column may numeric or strings.

when values strings, need assign unique id of string (unique across strings under same column; same id must assigned if same string appears elsewhere under same column).

what efficient way it?

use defaultdict default value factory generates new ids:

ids = collections.defaultdict(itertools.count().next) ids['a']  # 0 ids['b']  # 1 ids['a']  # 0 

when key in defaultdict, if it's not present, defaultdict calls user-provided default value factory value , stores before returning it.

collections.count() creates iterator counts 0, collections.count().next bound method produces new integer whenever call it.

combined, these tools produce dict returns new integer whenever you've never looked before.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -