Some simple usage of python dict

I thought I was very familiar with using dict, but when I actually used it again, I found that the foundation was too thin, and there were too many places that were prone to errors;

  • Creation of dict:
d = dict()
# or 更简单
d = {}

This creates a new dict that does not contain any key, value

  • Insertion and assignment of dict:
    If I don't know if there is a dict[key] in a dict object, I have to judge first: return a boolean variable
    withhas_key()
if d.han_key('key'):
    #do something...

An example:
For example, I have a list with repeated elements, and I want to count the number of occurrences of all elements

list = [1,2,2,3,4,2,3,3]
d = dict()
for element in list:
    if d.has_key(element):
        d[element] += 1
    else:
        d[element] = 1
  • Traversal of dict:
    a simple method, it Python2.7is used like this, just remember one
for k,v in dict.iteritems():
    print '%s:%s' % (k, v)

which iteritems()returns adictionary-itemiterator object

Compared items()to the returned list, each element of the list is a tuple, such as:

[('a', 1), ('b', 2)]
  • Sorting of dict:
    Sorting is actually converting the elements in the dict into a list, and each element of the list is a tuple; then operate on the list.

I thought about it carefully, does dict sorting make sense? What I mean is that I am committed to realizing that I put all the elements in order and put them back in order. This is unrealistic in itself, because the creation and maintenance of dict is not based on continuous memory, but hash.
So we can only get an ordered list, not an ordered dict.
So if you know the idea of ​​sorting, items()you can extract it and sort the list again.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325364214&siteId=291194637
Recommended