Home > Mobile >  How to add non-repeating elements in value of dictionary
How to add non-repeating elements in value of dictionary

Time:10-30

I want to put every five members of my list in a list as the value of my dictionary but the duplicate numbers should not be added in the individual values and I need to implement this program in Python in the shortest possible order.

For example if the list is lst = [9, 9, 9, 2, 3, 4, 5, 5, 6, 6], the result dictionary should be d = {1: [9, 2, 3], 2: [4, 5, 6]}.

Another example is lst = [8, 6, 1, 9, 1, 0, 2, 8] and the result dictionary is {1: [8, 6, 1, 9], 2: [0, 2, 8]}

CodePudding user response:

You can use a dictionary comprehension:

def fn(lst, n):
    return {
        idx: list(dict.fromkeys(lst[i : i   n]))
        for idx, i in enumerate(range(0, len(lst), n), start=1)
    }


print(fn([9, 9, 9, 2, 3, 4, 5, 5, 6, 6], 5))
print(fn([8, 6, 1, 9, 1, 0, 2, 8], 5))

output:

{1: [9, 2, 3], 2: [4, 5, 6]}
{1: [8, 6, 1, 9], 2: [0, 2, 8]}

Explanation:
You need to iterate through your list with the step of n. Then create your slice which contains n items. To remove duplicates I used dict.fromkeys() which preserves the insertion order. Also the keys are coming from enumerate(..., start=1)

CodePudding user response:

An approach chunking the original array and applying a dict.fromkeys in each chunk and converting to dict

a = [9,9,9,2,3,4,5,5,6,6]

def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i   n]

l = [list(dict.fromkeys(chunk)) for chunk in chunks(a,5)]

d = {k 1:v for k,v in enumerate(l)}

print(d)
  • Related