1

I wanted to use a dictionary both with the keys and also like lists with indexing. but i found that assignment to an dictionary is not in order.

my python script is:

left=['E','Z','T','Y','F']

for lhs in left:
  first[lhs]=set()
  follow[lhs]=set()
  print first

and i get the output as:

{'E': set([])}
{'Z': set([]), 'E': set([])}
{'Z': set([]), 'E': set([]), 'T': set([])}
{'Y': set([]), 'Z': set([]), 'E': set([]), 'T': set([])}
{'Y': set([]), 'Z': set([]), 'E': set([]), 'T': set([]), 'F': set([])}

one time it's inserted at end and another time it's at the beginning. this made me to think that i dont know the dictionary at all. where can i know the dictionary in depth. and how can iterate through a dictionary with keys as well as with indexes. for this i'm using now:

for lhs in left:
  print first[lhs]

this some how helps with indexing. but is there any other method?

RatDon
  • 3,403
  • 8
  • 43
  • 85
  • 2
    Python's `dict` does not maintain order. Use different solution, such as `OrderedDict`. – Tadeck Sep 11 '13 at 17:22
  • 2
    Here's a fascination presentation called [The Mighty Dictionary](http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2010-the-mighty-dictionary-55-3352147) from PyCon 2010 explaining the internals of how dictionaries are implemented. – Steven Rumbalski Sep 11 '13 at 17:33
  • possible duplicate of [Python dictionary, keep keys/values in same order as declared](http://stackoverflow.com/questions/1867861/python-dictionary-keep-keys-values-in-same-order-as-declared) – Steven Rumbalski Sep 11 '13 at 17:42
  • 1
    While Tadeck and chepner are correct that `OrderedDict` might serve your needs, you might also be fine with just doing your own sorting (if the order is only needed for presentation purposes, for example). The first thing to do is just familiarize yourself with `dict`. See the official [tutorial](http://docs.python.org/2/tutorial/datastructures.html#dictionaries) and [library reference](http://docs.python.org/2/library/stdtypes.html#mapping-types-dict) if you haven't already. – John Y Sep 11 '13 at 18:13
  • @Tadeck: Please post answers as answers, not as comments. – Ethan Furman Sep 11 '13 at 19:05
  • 1
    @EthanFurman: It was not an answer, just poorly written comment trying to start discussion on what OP could do and what he tried. From the question, I was not really sure, what is the goal of OP, so I did not consider my comment as an answer. – Tadeck Sep 11 '13 at 20:07

1 Answers1

6

Use collections.OrderedDict. It requires Python 2.7, but it remembers the order in which keys are added, rather than storing them in an arbitrary order based on the underlying hash algorithm.

Update: to be precise, the storage of the dict is unchanged, but the iteration is implemented with an additional data structure to provide a fixed order based on the original insertion order of the keys.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 2
    It still stores them in arbitrary order,Ordered dict is nothing but a dict + list.When an item is inserted, you add key to list as well as storing it in dict.So list preserves the order of keys. When ordered dict is iterated, it is done through elements of list. – Srinivas Reddy Thatiparthy Sep 11 '13 at 17:23
  • I never gave much thought to how it was implemented; I think I was assuming it was done at the C level. And not just a list, but a doubly-linked circular list with a dictionary to map keys to indices. That's a lot of engineering :) – chepner Sep 11 '13 at 17:30
  • Please change the answer, it could mislead people. – Srinivas Reddy Thatiparthy Sep 11 '13 at 17:33
  • 2
    @SrinivasReddyThatiparthy: But the `OrderedDict` class handles all of that transparently. There's not a *practical* difference between "remembers the order" and "stores in order". And at any time, the underlying implementation is free to change as long as the API is preserved. – John Y Sep 11 '13 at 17:34
  • @JohnY Your comment is on a generic level.Mine being python specific. – Srinivas Reddy Thatiparthy Sep 11 '13 at 17:37
  • 1
    @SrinivasReddyThatiparthy: My point is that if you're going to iterate over an `OrderedDict`, you're going to get the items in insertion order, regardless of the underlying implementation. This answer is not likely to mislead anyone. Anyone who might be affected by the underlying storage is almost definitely going to understand `dict` and `OrderedDict` well enough to know how to handle it and not be hurt by this answer. – John Y Sep 11 '13 at 18:03
  • @SrinivasReddyThatiparthy though it's a list + dictionaries, i'm unable to access using indexes like `c[0]` or `c[1]` – RatDon Sep 11 '13 at 19:05
  • 1
    @RatDon That's because it's a dictionary by nature... so it's `c[0]` is a call to `c.__getitem__` which tries to look it up by *key*.... not by *index*... In Py2.7 you can use `c.keys()` to get a list of the keys and index into that, in Py3.x you'd need to use `list(c.keys())` but if you wish to directly access by index and key, it might be worthwhile thinking why? – Jon Clements Sep 11 '13 at 19:14
  • 2
    Strictly speaking, an OrderedDict is simply a dict whose iteration is implemented using a supplemental data structure that is not user-accessible. (This being Python, the user *can* access it, but is not supposed to.) – chepner Sep 11 '13 at 19:40
  • @SrinivasReddyThatiparthy i'm using it in a parser for my study. a list say x is been iterated and up on satisfying a condition i'm adding a value to dictionary at same index as the item in x. x and dictionary has no link at all. so now i've to use item at same index of the list which is used to create the keys of dictionary and use that as a key of the dictionary. if the dictionary could have been indexed, it would be little easy to understand. – RatDon Sep 11 '13 at 23:04