I have a list and I want to generate a dictionary d
taking out duplicates and excluding a single item, such that the first key has value 0, the second has value 1, and so on.
I have written the following code:
d = {}
i = 0
for l in a_list:
if (l not in d) and (l != '<'):
d[l] = i
i += 1
If a_list = ['a', 'b', '<', 'c', 'b', 'd']
, after running the code d
contains {'a': 0, 'b': 1, 'c': 2, 'd':3}
. Order is not important.
Is there a more elegant way to obtain the same result?
Method #1 : Using get() The get function can be used to initialize a non-existing key with 0 and then the increment is possible. By this way the problem of non-existing key can be avoided.
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
Use dict.fromkeys
to get your unique occurrences (minus values you don't want), then .update
it to apply the sequence, eg:
a_list = ['a', 'b', '<', 'c', 'b', 'd']
d = dict.fromkeys(el for el in a_list if el != '<')
d.update((k, i) for i, k in enumerate(d))
Gives you:
{'a': 0, 'b': 1, 'd': 2, 'c': 3}
If order is important, then use collections.OrderedDict.fromkeys
to retain the ordering of the original values, or sort the unique values if they should be alphabetical instead.
{b: a for a, b in enumerate(set(a_list) - {'<'})}
set(a_list)
creates a set from a_list
.
That effectively strips duplicate numbers in a_list
, as a set
can only contain unique values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With