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

前端 未结 6 2402
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:34

    I wonder if it is an ordered dict that you want:

    >>> k = "one two three four five".strip().split()
    >>> v = "a b c d e".strip().split()
    >>> k
      ['one', 'two', 'three', 'four', 'five']
    >>> v
      ['a', 'b', 'c', 'd', 'e']
    >>> dx = dict(zip(k, v))
    >>> dx
       {'four': 'd', 'three': 'c', 'five': 'e', 'two': 'b', 'one': 'a'}
    >>> for itm in dx: 
            print(itm)
    
       four
       three
       five
       two
       one
    
    >>> # instantiate this data structure from OrderedDict class in the Collections module
    >>> from Collections import OrderedDict
    >>> dx = OrderedDict(zip(k, v))
    >>> for itm in dx:
            print(itm)
    
       one
       two
       three
       four
       five 
    

    A dictionary created using the OrderdDict preserves the original insertion order.

    Put another way, such a dictionary iterates over the key/value pairs according to the order in which they were inserted.

    So for instance, when you delete a key and then add the same key again, the iteration order is changes:

    >>> del dx['two']
    >>> for itm in dx:
            print(itm)
    
           one
           three
           four
           five
    
    >>> dx['two'] = 'b'
    >>> for itm in dx:
            print(itm)
    
           one
           three
           four
           five
           two
    

提交回复
热议问题