Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving elements in dictionary python to another index

If i have a dictionary like this for example:

dicta={1:['a','a','a'],2:['b,'b','b'],'N':['n','n','n'],3:['c','c','c']}

and i want the N to be in the last position as i convert this dict later on into a df. Is there a way to shift it down?

Finding the index of the N is fine: index=list(dicta.keys()).index('N')

but then how would you do the (in pseudo code) dicta.position[-1] = dicta[index] bit?

like image 209
matthewr Avatar asked Dec 18 '22 22:12

matthewr


1 Answers

If you're using CPython 3.6+, since dict are insertion-based ordered, you can move an item to the end by popping it and then re-assigning it to the dictionary.

>>> dicta = {1: 'a', 2: 'b', 'N': 'n', 3: 'c'}
>>> dicta['N'] = dicta.pop('N')
>>> dicta
{1: 'a', 2: 'b', 3: 'c', 'N': 'n'}

If you're using lower versions then you're outta luck!

like image 55
Mazdak Avatar answered Dec 20 '22 12:12

Mazdak