How to implement associative array (not dictionary) in Python?

前端 未结 6 2422
Happy的楠姐
Happy的楠姐 2020-12-17 21:57

I trying to print out a dictionary in Python:

Dictionary = {\"Forename\":\"Paul\",\"Surname\":\"Dinh\"}
for Key,Value in Dictionary.iteritems():
  print Key,         


        
6条回答
  •  渐次进展
    2020-12-17 22:44

    First of all dictionaries are not sorted at all nor by key, nor by value.

    And basing on your description. You actualy need collections.OrderedDict module

    from collections import OrderedDict
    
    my_dict = OrderedDict([("Forename", "Paul"), ("Surname", "Dinh")])
    
    for key, value in my_dict.iteritems():
        print '%s = %s' % (key, value)
    

    Note that you need to instantiate OrderedDict from list of tuples not from another dict as dict instance will shuffle the order of items before OrderedDict will be instantiated.

提交回复
热议问题