dictionary - Python Dict() with Id number -


I am new to dict (). I try an example (Python 2.6)

  Import from default collection order S = 'happy blues happy cry crazy mad sad' d = defaultdict (int) s.split () in k For: d [k] + = 1 print d.items ()  

Result:

  [('nuts', 1), (' I am surprised that what is the meaning of each word, 'sad', 2), ('crazy', 1), ('row', 1), ('happy', 2)]  

Is it possible to get an ID? any suggestion?

Expectation of results:

  [(1, 'crazy', 1), (2, 'sad', 2), (3, 'crazy', 1 ), (4, 'row', 1), (5, 'happy', 2)]  

You can add counting by using the result, but note that the command is meaningless because the dictionaries do not have any set order:

  [( I,) Items for + I, items in enumerate (d.items (), 1)]  

demo:

  & gt; & Gt; & Gt; Items for item (I,) + I, in enumerate (d.items (), 1)] [(1, 'crazy', 1), (2, 'miserable', 2), (3) Depending on the history of insertion and extinction instead of the dictionary order, it depends on the history of merger and extinction. You can not bring back key-value pairs in a particular order at  d.items () . 

The command does remains constant until you add or remove anything from the dictionary, and D.KIs () , D.values ​​() and D. items () will produce lists in the same order; zip (d.keys (), d.values ​​()) does the same code as d.items () . As soon as the dictionary itself is not changed, you can use a specific command for that specific dictionary value and do not trust it.


Comments