Alboali
By:
Alboali

dict() function isn't working properly on the cloud server (Python3)

September 20, 2017 179 views
Python Ubuntu 16.04

Hi, i'm having problem using python3 on my Ubuntu 16.04.3 x64 with the dict() function
when i use it on my own PC it works fine but on the cloud server isn't running well..

after sorting my dictionary with sotred() function i get this output (example):

[(1, {'car': 'red'}, 2, {'bike': 'green'}, 3, {'plane': 'white'})]

when i want it to turn the tuple to dictionary i use dict() (example):

dict([(1, {'car': 'red'}, 2, {'bike': 'green'}, 3, {'plane': 'white'})])

but when use the dict function it reorder everything randomly (example):

{2, {'bike': 'green'}, 3, {'plane': 'white'}, 1, {'car': 'red'}}

any idea why?

2 Answers

Show your test case and exact python versions for both platforms.

  • Python version:
    PC: 3.6.0
    Cloud: 3.5.2

    #!/usr/lib python3
    
    L = {3: {'iphone': 5}, 2: {'iphone': 4}, 4: {'iphone': 3}, 5: {'iphone': 6}, 6: {'iphone': 7}, 7: {'iphone': 1}, 8: {'iphone': 2}}
    
    # Sort dict on iphone numbers
    T = sorted(L.items(), key=lambda y: int(y[1]['iphone']))
    print(T) # print to check the result of sorted function
    
    D = dict(T)
    print(D) # check the tuple after changed to dictionary
    

    Result must be:

    {7: {'iphone': 1}, 8: {'iphone': 2}, 4: {'iphone': 3}, 2: {'iphone': 4}, 3: {'iphone': 5}, 5: {'iphone': 6}, 6: {'iphone': 7}}
    

Python's dict is not guaranteed to return items in the same order.
Try something like this if required:

#!/usr/lib python3
from collections import OrderedDict

L = {3: {'iphone': 5}, 2: {'iphone': 4}, 4: {'iphone': 3}, 5: {'iphone': 6}, 6: {'iphone': 7}, 7: {'iphone': 1}, 8: {'iphone': 2}}

# Sort dict on iphone numbers
T = sorted(L.items(), key=lambda y: int(y[1]['iphone']))
#print(T) # print to check the result of sorted function

D = OrderedDict(T)
print(D) # check the tuple after changed to dictionary
Have another answer? Share your knowledge.