Dictionary and Set

Dictionary

Dictionary is a unordered data structure which is a list of key-value pairs, searching speed fast, and the key of each pair is unique and un-updatable. *like JSON format

Why dict is faster than other collection
Dictionary is using more space(memory) to reduce time consumption, but like list which is using more time to reduce space consumption.

Create a dict
Each element is a key-value pair
example

//Code==========
d = {
    'Joanna': 100,
    'Lisa': 85,
    'Bart': 59,
    'Paul': 75
}
print(d)
//Result==========
{'Joanna': 100, 'Lisa': 85, 'Bart': 59, 'Paul': 75}

Length of dict
Actually not just dictionary, list, set, tuple alse have len() to get the length of collection
example

//Code==========
d = {
    'Joanna': 100,
    'Lisa': 85,
    'Bart': 59,
    'Paul': 75
}
print(len(d))
//Result==========
4

Access a element from the dict
Access element by key value, *if the key you used is not listed in keys of dict, you will get a 'KeyError' error, solution is check whether the key is existing in keys of dict

example

//Code==========
d = {
    'Joanna': 100,
    'Lisa': 85,
    'Bart': 59,
    'Paul': 75
}
print(d['Joanna'])
searchText = 'Bin'
if searchText in d:
    print(d[searchText])
else:
    print('cannot find',searchText)
//Result==========
100
cannot find Bin

Update a existing element from the dict
For updating a existing element, just override the value by using access element operator
example

//Code==========
d = {
    'Joanna': 100,
    'Lisa': 85,
    'Bart': 59,
    'Paul': 75
}
d['Joanna'] = 'A+'
print(d['Joanna'])
//Result==========
A+

Traverse the dict
There are several ways to traverse the dictionary, because dictionary has a lot built-in methods, and many of them returns iterator entities.
example

//Code==========
d = {
    'Joanna': 100,
    'Lisa': 85,
    'Bart': 59,
    'Paul': 75
}
for key in d.keys():
    print (key,':',d.get(key))
for key, value in d.items():
    print (key,':',value)
//Result==========(because results are same, here only list one time)
Joanna : 100
Lisa : 85
Bart : 59
Paul : 75

Set

We can say set is a uniqued and unordered list to regular list. Because its elements are uniqued, there is no element can appear twice.

Why set
We can use set when we need a checklist or any list which has unique elements. Like month-list, week-list, etc.

Create a set
You can use an existing list to convert to a set
example

//Code==========
s = set(['Joanna', 'Lisa', 'Bart', 'Paul'])
print(s)
//Result==========
{'Bart', 'Joanna', 'Lisa', 'Paul'}

Check key existing or not
Like dictionary, set also provides the method to check whether the element is existing in set
example

//Code==========
s = set(['Joanna', 'Lisa', 'Bart', 'Paul'])
print('Bin' in s)
//Result==========
False

Others are same to list

你可能感兴趣的:(Dictionary and Set)