字典 dict {}

字典(dictionary)是Python中另一个非常有用的内置数据类型。

列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

字典是一种映射类型,字典用 { } 标识,它是一个无序的 键(key) : 值(value) 的集合。

键(key)必须使用不可变类型:可以是int float str tuple,也可以是自定义对象,但不可以是list,set,dict

在同一个字典中,键(key)必须是唯一的。

dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2] = "2 - 菜鸟工具"

tinydict = {'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}

print(dict['one'])  # 输出键为 'one' 的值
print(dict[2])  # 输出键为 2 的值
print(tinydict)  # 输出完整的字典
print(tinydict.keys())  # 输出所有键 <class 'dict_keys'>
print(tinydict.values())  # 输出所有值 <class 'dict_values'>
print(tinydict.items()) # 输出所有item <class 'dict_items'>
print(type(dict.values()))

 

若要获取和设置字典的某一个值:

1、dict[key]  获取key对应的value,key不存在会出错

2、dict.get(key) 或 dict.get(key,defaultValue) ,获取key对应的value,key不存在返回None或defaultValue

3、dict[key] = xxx ,添加或修改key对应的value,key不存则添加,key存在了为修改

4、dict.setdefault(key,value),只能添加,不能修改,如果key已经存在,这条语句无效(不会出错)


birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
print(birthdays.get('tj')) # None
print(birthdays.get('tj',123)) # 123
# print(birthdays['tj']) # 出错:KeyError: 'tj'

birthdays['ttt'] = "tangjun" # 添加一个item
birthdays['ttt'] = "tangjun112" # 覆盖已有的item

birthdays.setdefault('aaa',123) # 添加一个item
birthdays.setdefault('aaa',444) # 如果key已经存在,不会覆盖已有的item

print(birthdays)
# {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4', 'ttt': 'tangjun112', 'aaa': 123}
 

 

补充:keys()和values()返回的值都是可以迭代的(能for in的都可以迭代)所以都可以把它们包装成list set tuple

dict1 = {'abc': 1, "cde": 2, "d": 4, "c": 567, "d": "key1"}
ks = dict1.keys()
t = tuple(ks)
l = list(ks)
s = set(ks)
# ('abc', 'cde', 'd', 'c') ['abc', 'cde', 'd', 'c'] {'d', 'c', 'cde', 'abc'}
print(t, l, s)

 

构造函数 dict() 可以直接从键值对序列中构建字典如下:

>>> dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])
{'Runoob': 1, 'Google': 2, 'Taobao': 3}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> dict(Runoob=1, Google=2, Taobao=3)
{'Runoob': 1, 'Google': 2, 'Taobao': 3}
>>>

 输入 dict 的键值对,可直接用 items() 函数

dict1 = {'abc':1,"cde":2,"d":4,"c":567,"d":"key1"}
for k,v in dict1.items():
    print(k,":",v)

# 说明:k,v =('abc',1) 这是一个把tuple自动拆包的过程

 关于字典推导式的一些案例:

# 字典推导式
p = {i:str(i) for i in range(1,5)}
print("p:",p)
'''
p: {1: '1', 2: '2', 3: '3', 4: '4'}
'''

x = ['A','B','C','D']
y = ['a','b','c','d']
n = {i:j for i,j in zip(x,y)}
print("n:",n)
'''
n: {'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd'}
'''

s = {x:x.strip() for x in ('he','she','I')}
print("s:",s)
'''
s: {'he': 'he', 'she': 'she', 'I': 'I'}
'''

 

另外,字典类型也有一些内置的函数,例如clear()、keys()、values()等。

注意:set 和 dict 都不可以进行+*运算,如果要合并两个set或dict,请用update()方法:

dict = {'Name': 'Runoob', 'Age': 7}
dict2 = {'Sex': 'female'}
dict.update(dict2)
print("更新字典 dict : ", dict)


# 下面的方法也可以合并两个字典
dict1 = {'a': 10, 'b': 8} 
dict2 = {'d': 6, 'c': 4}
d3 = {**dict1, **dict2}
print(d3) # {'a': 10, 'b': 8, 'd': 6, 'c': 4}
 

 {'Name': 'Runoob', 'Age': 7, 'Sex': 'female'}

另,可以用del命令删除字典元素或字典:del dict['Name']        del dict

 

字典排序

def dictionairy():
    key_value = {}
    # 初始化
    key_value[2] = 56
    key_value[1] = 2
    key_value[5] = 12
    key_value[4] = 24
    key_value[6] = 18
    key_value[3] = 323

    # 因为字典的无序的,所有字典没有sort()方法,但是我们可以根据自己的需要调用sorted()方法对字典进行排序
    # key_value.sort() 错,dict没有sort方法

    print(sorted(key_value))  # [1, 2, 3, 4, 5, 6]
    print(sorted(key_value.keys()))  # [1, 2, 3, 4, 5, 6]
    print(sorted((key_value.values())))  # [2, 12, 18, 24, 56, 323]
    print(sorted(key_value.items()))  # [(1, 2), (2, 56), (3, 323), (4, 24), (5, 12), (6, 18)]

    print("按键(key)排序:")
    for i in sorted(key_value):
        print((i, key_value[i]), end=" ")
    # (1, 2), (2, 56), (3, 323), (4, 24), (5, 12), (6, 18)

    print()
    print("按值(value)排序:")
    # 匿名函数把key和value的位置对换一下,或者直接返回value,key可以忽略。
    print(sorted(key_value.items(), key=lambda kv: kv[1]))
    # [(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]



dictionairy()

# 列表字典排序

lis = [{"name": "Taobao", "age": 100},
       {"name": "Runoob", "age": 7},
       {"name": "Google", "age": 100},
       {"name": "Wiki", "age": 200}]
# 用list的sort()方法排序:会改变原来list的顺序
print("用list的sort()方法排序: ")
lis.sort(key=lambda item:item['age'],reverse=True)
print(lis)

#  用全局函数sorted排序:不会改变原来list的顺序,而是返回一个新的list
# 通过 age 升序排序
print("列表通过 age 升序排序: ")
l = sorted(lis, key=lambda i: i['age'])
print(l)
print(lis)

# 先按 age 排序,再按 name 排序
print("列表通过 age 和 name 排序: ")
print(sorted(lis, key=lambda i: (i['age'], i['name'])))



# 按 age 降序排序
print("列表通过 age 降序排序: ")
print(sorted(lis, key=lambda i: i['age'], reverse=True))


# 列表通过 age 升序排序:
# [{'name': 'Runoob', 'age': 7}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Wiki', 'age': 200}]
#
# 列表通过 age 和 name 排序:
# [{'name': 'Runoob', 'age': 7}, {'name': 'Google', 'age': 100}, {'name': 'Taobao', 'age': 100}, {'name': 'Wiki', 'age': 200}]
#
# 列表通过 age 降序排序:
# [{'name': 'Wiki', 'age': 200}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Runoob', 'age': 7}]

 

posted @ 2020-09-30 08:58  老谭爱blog  阅读(383)  评论(0)    收藏  举报