OrderedDict for older versions of python

前端 未结 7 2139
春和景丽
春和景丽 2020-11-27 17:59

Ordered dictionaries are extremely useful structures, but unfortunately these are quite recent only working in versions from 3.1 and 2.7. How can I use an ordered dictionary

7条回答
  •  悲哀的现实
    2020-11-27 18:24

    Also, you could just program your way around it if your situation allows:

    def doSomething(strInput): return [ord(x) for x in strInput]
    
    things = ['first', 'second', 'third', 'fourth']
    
    oDict = {}
    orderedKeys = []
    for thing in things:
        oDict[thing] = doSomething(thing)
        orderedKeys.append(thing)
    
    for key in oDict.keys():
        print key, ": ", oDict[key]
    
    print
    
    for key in orderedKeys:
        print key, ": ", oDict[key]
    

    second : [115, 101, 99, 111, 110, 100]
    fourth : [102, 111, 117, 114, 116, 104]
    third : [116, 104, 105, 114, 100]
    first : [102, 105, 114, 115, 116]

    first : [102, 105, 114, 115, 116]
    second : [115, 101, 99, 111, 110, 100]
    third : [116, 104, 105, 114, 100]
    fourth : [102, 111, 117, 114, 116, 104]

    You could embed the ordered keys in your Dictionary too, I suppose, as oDict['keyList'] = orderedKeys

提交回复
热议问题