Python Exercise task6: dictionaries and collections

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/zyc_001117/article/details/102763672

dictionary

Sequences, which are integer indexes, and this difference is, the dictionary to "key" for the index key can be any immutable type , usually a string or numeric. Python is only a dictionary mapping type, a string, a tuple, a list of sequences belonging to the type.
So how do you determine whether a data type variable? There are two ways:
1. by ID (X) function, some kind of operation X, id compared before and after the operation, if not the same, then X can not be changed, if the same, then X variable.

i=1
print(id(i))
i=i+2
print(id(i))

Here Insert Picture Description
After the addition integer i id 2 and not the same as before, so the integer data type can not be changed.

l=[1,2]
print(id(l))
l.append('abc')
print(id(l))

Here Insert Picture Description
L in the list before and after the additional id 'Python' the same, so the list is changeable.
2. Use the hash (X), as long as no error, X may be demonstrated hash, i.e. can not be changed, can not be hashed in turn, can change.

print(hash(3))
print(hash('Python'))
print(hash((1,2,'abc')))
print(hash([1,2,'abc']))

Here Insert Picture Description
There can be seen running result integer, string and tuple hash can be used, without error, and use the hash list on the error, the data type known integers, strings and tuples are immutable, and the list is Variable.

The dictionary definition of grammar

{元素1, 元素2, ..., 元素n}

Note:
1. in which each element is a key-value pair - key: value (Key: value)
2. The key point is that the braces "{}", comma "," and the colon ":"
3. braces all elements tied together, comma separated one by one for each key, and the key values separating colon

Create and access dictionary

A dictionary is unordered collection of key-value pairs in a dictionary in the same key must be different from each other.

dict={'Monday':'星期一','Tuesday':'星期二','Wednesday':'星期三'}
print(dict)
print(dict['Tuesday'])

Here Insert Picture Description

Dictionary built-in methods

dict.fromkeys (seq, value) for creating a new dictionary, the sequence elements do seq dictionary key, value corresponding to all the keys to the dictionary initial value.

seq=('name','age','gender')
dict=dict.fromkeys(seq)
print(dict)
dict=dict.fromkeys(seq,('Meng'))
print(dict)
dict=dict.fromkeys(seq,('Meng','12','M'))
print(dict)

Here Insert Picture Description
dict.keys () returns an iterator object may be used list () to convert into a list.

dict={'name':'Meng','age':'18'}
print(dict.keys())
print(list(dict.keys()))

Here Insert Picture Description
dict.values ​​() returns an iterator can be used list () converts a list, a list of all values ​​for the dictionary.

dict={'name':'Meng','age':'18'}
print(dict.values())
print(list(dict.values()))

Here Insert Picture Description
dict.items () Returns a list traversal (key, value) tuples array .

dict={'name':'Meng','age':'18'}
print('value:',dict.items())  
print(tuple(dict.items()))  

Here Insert Picture Description
dict.get (key, default = None) Returns the specified key, if the value is not in the dictionary returns the default value.

dict={'name':'Meng','age':'18'}
print('name的值为:',dict.get('name'))  
print('gender的值为:',dict.get('gender','M'))  

Here Insert Picture Description
key in dict in operator for determining whether there is a key, returns true if the key in the dictionary in the dictionary dict, otherwise returns false. The operator is not in exactly the opposite, if the key is in the dictionary dict returns false, otherwise returns true.

dict={'name':'Meng','age':'18'}
if 'name' in dict:
    print("键name存在")
else:
    print("键name不存在")
if 'sex' not in dict:
    print("键sex不存在")
else:
    print("键sex存在")

Here Insert Picture Description
dict.clear () removes all elements in the dictionary.

dict={'name':'Meng','age':'18'}
print("字典长度:",len(dict))
dict.clear()
print("字典删除后长度:",len(dict))

Here Insert Picture Description
dict.copy () Returns a shallow copy of the dictionary.

dict={'name':'Meng','age':'18'}
dict2=dict.copy()
print(dict2)

Here Insert Picture Description
dict.pop (key, default) value of a given dictionary delete key corresponding to the key, the return value is deleted .
key value must be given. Otherwise, return default values.

dict={'name':'Meng','age':'18'}
dict.pop('name')
print(dict)

Here Insert Picture Description
del dict [key] dictionary delete key to a value corresponding to the given key.

dict={'name':'Meng','age':'18'}
del dict['name']
print(dict)

Here Insert Picture Description
dict.popitem()随机返回并删除字典中的一对键和值,如果字典已经为空,却调用了此方法,就报出KeyError异常。

dict={'name':'Meng','age':'18'}
dict.popitem()
print(dict)

Here Insert Picture Description
dict.setdefault(key, default=None)和get()方法 类似, 如果键不存在于字典中,将会添加键并将值设为默认值。

dict={'name':'Meng','age':'18'}
print("name键的值为:",dict.setdefault('name', None))
print("Sex 键的值为:",dict.setdefault('Sex', None))
print("新字典为", dict)  

Here Insert Picture Description
dict.update(dict2)把字典参数 dict2 的 key/value(键/值) 对更新到字典 dict 里。

dict={'name':'Meng','age':'18'}
dict2={'gender':'M','age':'19'}
dict.update(dict2)
print("更新字典dict:", dict)

Here Insert Picture Description

集合

与dict类似,set也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。

集合的创建

直接把一堆元素用花括号括起来{元素1, 元素2, …, 元素n},重复元素在set中会被自动被过滤。

set={'cat','dog','rabbit'}
print(set) 

Here Insert Picture Description
使用set(value)工厂函数,把列表或元组转换成集合。

a = set('rabbit')
print(a)
b = set(('rabbit','cat','dog','rabbit'))
print(b)  
c = set(['rabbit','cat','dog','rabbit'])
print(c)  

Here Insert Picture Description
从结果发现集合的两个特点:无序 (unordered) 和唯一 (unique)。由于 set 存储的是无序集合,所以我们没法通过索引来访问,但是可以判断一个元素是否在集合中。

集合的内置方法

set.add(elmnt)用于给集合添加元素,如果添加的元素在集合中已存在,则不执行任何操作。

a = {'rabbit','cat','dog'}
a.add('rabbit')
print(a)
a.add('apple')
print(a)

Here Insert Picture Description
set.remove(item)用于移除集合中的指定元素。

a = {'rabbit','cat','dog'}
a.remove('rabbit')
print(a)

Here Insert Picture Description
set.update(set)用于修改当前集合,可以添加新的元素或集合到当前集合中,如果添加的元素在集合中已存在,则该元素只会出现一次,重复的会忽略。

a={'rabbit','cat','dog'}
b={'google', 'baidu','dog'}
a.update(b)
print(a)  

Here Insert Picture Description
由于 set 是无序和无重复元素的集合,所以两个或多个 set 可以做数学意义上的集合操作。set.intersection(set1, set2 …)用于返回两个或更多集合中都包含的元素,即交集。set.union(set1, set2…)返回两个集合的并集,即包含了所有集合的元素,重复的元素只会出现一次。set.difference(set) 返回集合的差集,即返回的集合元素包含在第一个集合中,但不包含在第二个集合(方法的参数)中。

a={'rabbit','cat','dog'}
b={'google', 'baidu','dog'}
print(a & b)
c = a.intersection(b)
print(c)
c = a.union(b)
print(c)
c = a.difference(b)
print(c)

Here Insert Picture Description
Are all the elements set.issubset (set) for determining the set are included in the specified collection , if it returns True, otherwise False.

a={'rabbit','cat','dog'}
b={'google', 'baidu','dog','rabbit','cat'}
print(a.issubset(b))
#True

Are all the elements set.issuperset (set) for determining the specified collection are included in the original collection , if it returns True, otherwise False.

x = {"f", "e", "d", "c", "b"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)  # False

frozenset ([iterable]) Returns a collection of frozen, frozen after collection can not add or delete any elements.

a={'rabbit','cat','dog'}
b=frozenset(a)
print(a)

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/zyc_001117/article/details/102763672