Getting a single dictionary item in Python

I only want to get the fourth element in the "e" dictionary (below).

I tried using the OrderedDict () method, but it didn't work. Here are my results:

from collections import OrderedDict

e = OrderedDict()
e = {'a': 'A',
     'b': 'B',
     'c': 'C',
     'd': 'D',
     'e': 'E'
    }

for k, v in e.items():
    print k, v

print e.items()[3]

      

The last line returns: ('e', 'E')

So, I translated the keys and values ​​into lists, but this is how the lists appeared when I typed them:

['a', 'c', 'b', 'e', 'd']


['A', 'C', 'B', 'E', 'D']

      

For me, it explained why it happened, but not how it happened.

So then I sorted them. This gave me the results I was looking for - but it seemed unnecessarily complex:

e = {'a': 'A',
     'b': 'B',
     'c': 'C',
     'd': 'D',
     'e': 'E'
}
k, v = sorted(e.keys()), sorted(e.values())
print "{}: {}".format(k[3], v[3])

      

Result: d: D

OrderedDict () is not required.

Is there an easier way to do this? And can someone explain why the elements in the dictionary are ordered like this:

keys: 'a', 'c', 'b', 'e', 'd'


values: 'A', 'C', 'B', 'E', 'D'

      

... which doesn't match the structure of my original dictionary?

+3


source to share


1 answer


You are not using an ordered dict.

e = OrderedDict()
e = {'a': 'A',
     'b': 'B',
     'c': 'C',
     'd': 'D',
     'e': 'E'
    }

      

The first line creates OrderedDict

. The second line discards it and replaces it with a regular dict, which is unordered. (Python variables are typeless.)

But you can't just do this:

e = OrderedDict({'a': 'A', ...})

      

... because it's still a regular dict that's still unordered and OrderedDict

can't magically recreate the original source order.

Try the following:



e = OrderedDict([('a', 'A'), ('b', 'B'), ...])

      

You should now have an object of type dict with the desired order.

And can someone explain why the elements in the dictionary are ordered like this ... which defies the structure of my original dictionary?

Because the dictionaries are unordered. They are just hash cards, and hash cards have no inherent ordering.


Note that you can also do this, which will preserve the pairing of keys and values ​​(whereas your separate sorts won't):

print sorted(e.items())[3]

      

+5


source







All Articles