Alexxio
Alexxio

Reputation: 1101

Get a dict from a python list

I have a list my_list = ['a', 'b', 'c', 'd'] and I need to create a dictionary which looks like

{ 'a': ['a', 'b', 'c', 'd'], 
  'b': ['b', 'a', 'c', 'd'], 
  'c': ['c', 'a', 'b', 'd'], 
  'd': ['d', 'a', 'b', 'c'] }

each element as its value being the list but the first element is itself.

Here is my code

my_list = ['1', '2', '3', '4']
my_dict=dict()

for x in my_list:        
    n = my_lst[:]
    n.remove(x)
    n= [x] + n[:]
    my_dict[x] = n

print my_dict

which gives

{'1': ['1', '2', '3', '4'], 
 '3': ['3', '1', '2', '4'], 
 '2': ['2', '1', '3', '4'], 
 '4': ['4', '1', '2', '3']}

as required. But I don't think that's the most optimal way of doing it. Any help to optimize will be appreciated.

Upvotes: 3

Views: 159

Answers (3)

donkopotamus
donkopotamus

Reputation: 23186

A faster approach (than the accepted answer) for larger lists is

{e: [e] + seq[:i] + seq[i+1:] for i, e in enumerate(seq)}

Relative timings:

In [1]: seq = list(range(1000))

In [2]: %timeit {e: [e]+[i for i in seq if i != e] for e in seq}
10 loops, best of 3: 40.8 ms per loop

In [3]: %timeit {e: [e] + seq[:i] + seq[i+1:] for i, e in enumerate(seq)}
100 loops, best of 3: 6.03 ms per loop

Upvotes: 2

horns
horns

Reputation: 1933

You can get hacky with a dictionary comprehension:

my_dict = {elem: list(sorted(my_list, key=lambda x: x != elem)) for elem in my_lst}

This works on the fact that the sorted function performs a stable sort, and False is less than True

Edit: This method is less clear and probably slower, use with caution.

Upvotes: 1

Matt Anderson
Matt Anderson

Reputation: 19769

>>> seq
    ['a', 'b', 'c', 'd']

>>> {e: [e]+[i for i in seq if i != e] for e in seq}
    {'a': ['a', 'b', 'c', 'd'],
     'b': ['b', 'a', 'c', 'd'],
     'c': ['c', 'a', 'b', 'd'],
     'd': ['d', 'a', 'b', 'c']}

Upvotes: 7

Related Questions