0

So I need to rearrange some values in my dictionary. Specifically, for 'Verb', the list comes before 'verb three', and I'd like it to come right after. I'm trying to use the foo[i], foo[j] = foo[j], foo[i] swapping method on a dummy list which I'll then assign over the original. Like so:

test_dict = {'Noun': ['noun one', 'noun two', 'noun three'], 
             'Verb': ['verb one', 'verb two', ['list one', 'list two',
                      'list three'], 'verb three', 'verb four']}

e = test_dict

for key in sorted(e):
    fixed_list = e[key]
    print('    ', key)
    for i in range(0, len(e[key])):
        print(i)
        print(type(e[key][i]))    
        if type(e[key][i]) == list:  
            print('ooh, this one\'s a list!', e[key][i])
            print('   and here it is in fixed_list: ', fixed_list[i])
            fixed_list[i], fixed_list[i+1] = fixed_list[i+1], fixed_list[i]
    e[key] = fixed_list

However, the bizarre output I get is [Note: the list in my 'Verb' key will never come last, so ignore the IndexError]:

 Noun
0
<class 'str'>
1
<class 'str'>
2
<class 'str'>

 Verb
0
<class 'str'>
1
<class 'str'>
2
<class 'list'>
ooh, this one's a list! ['list one', 'list two', 'list three']
and here it is in fixed_list:  ['list one', 'list two', 'list three']
3
<class 'list'>
ooh, this one's a list! ['list one', 'list two', 'list three']
and here it is in fixed_list:  ['list one', 'list two', 'list three']
4
<class 'list'>
ooh, this one's a list! ['list one', 'list two', 'list three']
and here it is in fixed_list:  ['list one', 'list two', 'list three']
Traceback (most recent call last):
File "/home/ubuntu/workspace/my_project.py", line 567, in <module>
fixed_list[i], fixed_list[i+1] = fixed_list[i+1], fixed_list[i]
IndexError: list index out of range

Now, unless I'm crazy, it seems like reassigning elements of fixed_list is causing issues in the key's value list inside the inner loop, but how? The only time they 'touch' each other assignment-wise is at the beginning and end of the outer loop.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Luke McPuke
  • 354
  • 1
  • 2
  • 12

0 Answers0