python - 字典(dict)

字典(dict):基于哈希表的一种数据结构,从原理上来说,与其它语言中的 map 是同一类东西。

# 创建一个空字典
import json

ordered_dict = {'a': 1}

print(ordered_dict)

# 向字典中添加一些键值对
ordered_dict['b'] = 2
ordered_dict['c'] = 3
ordered_dict['d'] = 4

print(ordered_dict.get('a'))
print(ordered_dict['a'])

# 几种遍历方式

for key in ordered_dict:
    print(key, ordered_dict[key])

for key in ordered_dict.keys():
    print(key)

for value in ordered_dict.values():
    print(value)

for key, value in ordered_dict.items():
    print(key, value)

# 字典合并

dict1 = {'name': 'ming', 'age': 18}
dict2 = {'class': 'No.1', 'age': 20}

print({**dict1, **dict2})
print(dict1 | dict2)

# json 序列化和反序列化

gson = json.dumps(ordered_dict)
print(gson)
print(json.loads(gson))

print('hello world!!')

字典的 key 是无序的,如果期望它是有序的,可以使用 collections 工具,

有序指的是插入的顺序,高版本的 python 的普通字典也保证了顺序。

(如果发现没有区别,可能只是 python 版本太高了,业务上,为了代码的健壮性,还是要是用工具包)

import collections

linked_map = collections.OrderedDict()
linked_map['d'] = 4
linked_map['b'] = 2
linked_map['a'] = 1
linked_map['c'] = 3
print(linked_map)

print('hello world!!')

冷门语法

# 将元组或列表,转为 index 为 key 的字典
params = {str(idx): value for idx, value in enumerate(args)}

posted on 2024-12-02 10:33  疯狂的妞妞  阅读(15)  评论(0编辑  收藏  举报

导航