Comparison of Dict and Set in Python

a dict

(list and tuple summary: click to open the link )

We already know that lists and tuples can be used to represent sequential sets, for example, the names of classmates:

['Adam', 'Lisa', 'Bart']

Or a list of test scores:

[95, 85, 59]

However, it is inconvenient to use two lists to find the corresponding grades according to the name. If we associate names with scores, we form a similar lookup table:

'Adam' ==> 95
'Lisa' ==> 85
'Bart' ==> 59

Given a name, you can directly look up the score. Python's dict is dedicated to doing this, which is equivalent to HashMap. The lookup table for "name"-"grade" in  dict  is as follows:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}

We call the name the key , the corresponding score is called the value , and the dict is to find the value through the key . Curly braces {} indicate that this is a dict, and then write it out according to key: value . The comma at the last key: value can be omitted. Since dict is also a collection, the len()  function can calculate the size of any collection. Note: One key-value counts as one, so the dict size is 3.

>>> len(d)
3

Features of dict:

1. The search speed is fast , whether the dict has 10 elements or 100,000 elements, the search speed is the same . The search speed of the list gradually decreases as the number of elements increases. However, the fast search speed of dict is not without cost. The disadvantage of dict is that it occupies a large amount of memory and wastes a lot of content . List is just the opposite, occupying less memory, but the search speed is slow. Since the dict is searched by key, in a dict, the key cannot be repeated .

2. The stored key-value pairs are not ordered ! This is not the same as list:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}

When we try to print this dict:

>>> print d
{'Lisa': 85, 'Adam': 95, 'Bart': 59}

The order of printing is not necessarily the order in which we created it, and different machines may print in different order, which means that dict is unordered internally , and dict cannot be used to store ordered collections.

3. The elements used as keys must be immutable . The basic types of Python such as strings, integers, and floating-point numbers are immutable and can be used as keys. But the list is mutable and cannot be used as a key. Immutable This restriction only applies to the key, it doesn't matter whether the value is mutable or not:

{
    '123': [1, 2, 3], # key is str, value is list 
    123: '123',   # key is int, value is str 
    ('a', 'b'): True   # key is tuple, And each element of the tuple is an immutable object, and the value is a boolean 
}

The most commonly used key is a string, because it is the most convenient to use.

two set

The function of dict is to establish a mapping relationship between a set of keys and a set of values. The keys of dict cannot be repeated. Sometimes, we only want the key of the dict, and don't care about the value corresponding to the key. The purpose is to ensure that the elements of this set will not be repeated. At this time, set comes in handy. A set holds a series of elements, which is similar to a list, but the elements of the set are not repeated and are unordered, which is very similar to the key of a dict. The way to create a set is to call set() and pass in a list, and the elements of the list will be used as the elements of the set:

>>> s = set(['A', 'B', 'C'])

You can view the contents of the set:

>>> print s
set(['A', 'C', 'B'])

Please note that the above printing form is similar to a list, but it is not a list. If you look closely, you can find that the order of printing may be different from the order of the original list, because the elements stored in the set are unordered .

Since a set cannot contain duplicate elements , what happens when we pass in a list that contains duplicate elements?

>>> s = set(['A', 'B', 'C', 'C'])
>>> print s
set(['A', 'C', 'B'])
>>> len(s)
3

The results show that set will automatically remove duplicate elements. The original list has 4 elements, but the set has only 3 elements.

Features of set:

1. The internal structure of set is very similar to that of dict. The only difference is that it does not store value . Therefore, it is very fast to judge whether an element is in the set.

2. The elements stored in a set are similar to the keys of a dict, and must be immutable objects . Therefore, any mutable objects cannot be placed in the set.

3. The elements stored in the set are also in no order.

Guess you like

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