字典
字典使用名称—内容进行数据结构的构建,在Python中分别对应着键(key)—值(value),习惯上称为键值对,下面举个例子:
city_popularity={'上海':'first','北京':'second','杭州':'third'}
上面就是字典的写法,那么我们来一一试验字典的性质:
city_popularity={'上海':'first','北京':'second','杭州':'third'}
city_popularity['深圳']='fourth'
print(city_popularity)
# {'上海':'first','北京':'second','杭州':'third','深圳':'fourth'}
这是字典元素的添加
city_popularity={'上海':'first','北京':'second'}
city_popularity.update({'杭州':'third','深圳':'fourth'})
print(city_popularity)
# {'上海':'first','北京':'second','杭州':'third','深圳':'fourth'}
添加多个元素用update()方法
city_popularity={'上海':'first','北京':'second','杭州':'third'}
del city_popularity['杭州']
print(city_popularity)
# {'上海':'first','北京':'second'}
删除字典中元素可以用del方法
city_popularity={'上海':'first','北京':'second','杭州':'third'}
print(city_popularity['上海'])
# first
注意字典中只能用相应键来获得对应值,不能用索引
集合
集合中元素是无序的而且各不相同,所以不能用索引和切片
只可以添加和删除其中的元素,例如:
a={1,2,3,4}
a.add(5)
print(a)
# {1,2,3,4,5}
a.discard(5)
print(a)
# {1,2,3,4}
上面是添加和删除集合元素的例子