matthewr
matthewr

Reputation: 324

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?

Upvotes: 6

Views: 17685

Answers (3)

PKRacha
PKRacha

Reputation: 21

It can also be done with the collections.OrderedDict and its method OrderedDict.move_to_end() with keyword argument last set to True.

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

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!

Upvotes: 22

BlackJack
BlackJack

Reputation: 4679

When the order of the dictionaty cannot be relied on (Python <3.7) you also should make sure the numbers are sorted. You could take the keys, remove the 'N', sort the remaining keys, and append the 'N' afterwards. Then use this list as explicit column argument to the DataFrame:

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

In [17]: columns = list(dicta.keys())

In [18]: columns.remove('N')

In [19]: columns.sort()

In [20]: columns.append('N')

In [21]: pd.DataFrame(dicta, columns=columns)
Out[21]: 
   1  2  3  N
0  a  b  c  n
1  a  b  c  n
2  a  b  c  n

Upvotes: 0

Related Questions