简体   繁体   中英

How to return a value of a key from a dictionary in python

Let me have a dictionary:

P={'S':['dB','N'],'B':['C','CcB','bA']}

How can I get second value o the second key from dictionary P ?

Also, if the value is a string with more than one character like 'bA' (third value of key 'B'), can I somehow return first character of this value ?

Like @jonrsharpe has stated before, dictionaries aren't ordered by design.

What this means, is that everytime you attempt to access a dictionary "by order" you may encounter a different result.

Observe the following (python interactive interpreter):

>>>P={'S':['dB','N'],'B':['C','CcB','bA'], 'L':["qqq"]}
>>>P.keys()
['S', 'B', 'L']

Its easy to see that in this notice, the "order" as we defined is, matches the order that we receive from the Dictionary.keys() function.

However, you may also observe this result:

>>> P={'S':['dB','N'],'B':['C','CcB','bA'], 'L':["qqq"], 'A':[]}
>>> P.keys()
['A', 'S', 'B', 'L']

In this example, the value 'A' should be fourth in our list, but, it is actually the first value.

This is just a small example why you may not treat dictionaries as ordered lists. Maybe you could go ahead and tell us what your intentions are and an alternative may be suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM