What's the simplest way to convert a set into a dict? Say from {'a', 'b'} into {'a': 0, 'b': 1}? Ordering doesn't matter but it should start from 0 up to the size of the set itself.
What's the simplest way to convert a set into a dict? Say from {'a', 'b'} into {'a': 0, 'b': 1}? Ordering doesn't matter but it should start from 0 up to the size of the set itself.
Just use dictionary comprehension with enumerate
>>> s = {'a', 'b'}
>>> {k:idx for idx,k in enumerate(s)}
{'a': 0, 'b': 1}
Just use the dict constructor with zip and range:
>>> s = {'a', 'b'}
>>> dict(zip(s, range(len(s))))
{'b': 0, 'a': 1}
And a similar approach, using itertools.count:
>>> from itertools import count
>>> dict(zip(s, count()))
{'b': 0, 'a': 1}
You can use enumerate:
set1={'a', 'b'}
dict1={j:i for i,j in enumerate(set1)}
print(dict1)
Output:
{'b': 0, 'a': 1}
>>> a = {'a', 'b'}
>>> dic = {i:val for val, i in enumerate(a)}
>>> dic
{'b': 0, 'a': 1}