java and python equivalent of php's foreach($array as $key => $value)

前端 未结 8 1045
抹茶落季
抹茶落季 2020-12-20 11:56

In php, one can handle a list of state names and their abbreviations with an associative array like this:



        
8条回答
  •  -上瘾入骨i
    2020-12-20 12:30

    Along the lines of Alexander's answer...

    The native python dictionary doesn't maintain ordering for maximum efficiency of its primary use: an unordered mapping of keys to values.

    I can think of two workarounds:

    1. look at the source code of OrderedDict and include it in your own program.

    2. make a list that holds the keys in order:

      states = ['Alabamba', 'Alaska', ...]  
      statesd = {'Alabamba':'AL', 'Alaska':'AK', ...}
      for k in states:
          print "The abbreviation for %s is %s." % (k, statesd[k])
      

提交回复
热议问题