Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a dictionary with incrementing values

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?

like image 465
aretor Avatar asked Aug 01 '17 15:08

aretor


People also ask

How do you increment a dictionary?

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.

How do you create a dictionary using multiple values?

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.


2 Answers

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.

like image 121
Jon Clements Avatar answered Sep 27 '22 20:09

Jon Clements


{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.

like image 29
qnnnnez Avatar answered Sep 27 '22 20:09

qnnnnez