Python dictionary related operations-add, delete, modify, search & sort

Recently, I did some code exercises for python dictionary operations, and by the way, I reorganized the various operations on the dict type and put them here for your reference.

Mainly includes the following contents:

  1. Create dictionary

  1. Dictionary comprehension usage

  1. Use of get(), fromkeys() and setdefault() methods

  1. How to use update()

  1. Methods to obtain dictionary key, value, items and loop printing

  1. member operations

  1. Dictionary sort

The code DEMO is as follows:

# 创建字典的四种方法 =============================
# 方法一:直接创建
dict_1 = {"Sun": "Sunday", "Mon": "Monday"}
print(dict_1)  # {'Sun': 'Sunday', 'Mon': 'Monday'}
# 方法二:使用dict()方法创建
dict_2 = dict(one=1, two=2)
print(dict_2)  # {'one': 1, 'two': 2}
# 方法三:在字典中添加新值
dict_3 = {}
dict_3["China"] = "Beijing"
dict_3["Germany"] = "Berlin"
print(dict_3)  # {'China': 'Beijing', 'Germany': 'Berlin'}
# 方法四:使用字典推导式
dict_4 = {i: object() for i in range(4)}
print(dict_4)
# {0: <object object at 0x0000015E8C5F4DB0>, 1: <object object at 0x0000015E8C5F4B90>,
# 2: <object object at 0x0000015E8C5F4BA0>, 3: <object object at 0x0000015E8C5F4BB0>}


# 字典推导式用法 =============================
capitals = {"Bratislava": 424207, "Vilnius": 556723, "Lisbon": 564657,
            "Riga": 713016, "Jerusalem": 780200, "Warsaw": 1711324,
            "Budapest": 1729040, "Prague": 1241664, "Helsinki": 596661,
            "Yokyo": 13189000, "Madrid": 3233527}

capitals_new = {k: v for k, v in capitals.items() if v < 1000000}
print(capitals_new)
# {'Bratislava': 424207, 'Vilnius': 556723, 'Lisbon': 564657,
# 'Riga': 713016, 'Jerusalem': 780200, 'Helsinki': 596661}


# get() , fromkeys()和setdefault()方法的使用 =============================
basket = ('oranges', 'pears', 'apples', 'bananas')
fruits = {}.fromkeys(basket, 0)
# fromkeys()方法创建一个新的词典,列表项将作为关键字。每个键都将初始化为 0。
# 请注意fromkeys()方法是一个类方法,需要调用该类名,在本例中为{}。
print(fruits)
fruits['oranges'] = 12
fruits['pears'] = 8
fruits['apples'] = 4

print(fruits.setdefault('oranges', 11))  # 12
# 'oranges' 键存在于词典中。 在这种情况下,该方法将返回其值。

print(fruits.setdefault('kiwis', 11))  # 12
# 键尚不存在。 一对新的 'kiwis': 11被插入字典。 值11被打印到控制台。

print(fruits)  # {'oranges': 12, 'pears': 8, 'apples': 4, 'bananas': 0, 'kiwis': 11}
# dict.get()方法,当字典中包含对应的键时,返回该键的值,如果没有该键,返回自定义值
print(fruits.get('apples', 'undefined'))  # 4
print(fruits.get('cherry', 'undefined'))  # undefined


# update()使用方法 =============================
dict_a = {"one": "1"}
dict_b = {"two": "2"}
dict_a.update(dict_b)  # 使用update()方法将 dict_b 字典添加到 dict_a 字典中
print(dict_a)  # {'one': '1', 'two': '2'}


# 删除字典中的元素 =============================
items = {"coins": 7, "pens": 3, "cups": 2, "bags": 1, "bottles": 4, "books": 5}
item = items.pop("coins")  # 返回被删除的coins键对应的值 7
print("Item having value {0} was removed".format(item))  # Item having value 7 was removed
print(items)  # {'pens': 3, 'cups': 2, 'bags': 1, 'bottles': 4, 'books': 5}
del items['books']  # del关键字从项目字典中删除"books": 5
print(items)
print(items.clear())  # clear()方法清除字典中的所有项目


# 获取字典key , value ,items 的方法 =============================
domains = {"de": "Germany", "sk": "Slovakia", "hu": "Hungary",
           "us": "United States", "no": "Norway"}
print(domains.keys())
# dict_keys(['de', 'sk', 'hu', 'us', 'no'])

print(domains.values())
# dict_values(['Germany', 'Slovakia', 'Hungary', 'United States', 'Norway'])

print(domains.items())
# dict_items([('de', 'Germany'), ('sk', 'Slovakia'), ('hu', 'Hungary'), ('us', 'United States'), ('no', 'Norway')])

# 循环打印 =============================
print("循环打印字典 key:")
for key in domains:
    print(key)

print("循环打印字典 value:")
for value in domains.values():
    print(value)

print("以k:v形式循环打印字典内容:")
for k1, v1 in domains.items():
    print(": ".join((k1, v1)))


# 使用 in 和 not in 检查字典中是否存在键(成员运算) =============================
print("de" in domains)  # True
print("sk" not in domains)  # False
print("ab" in domains)  # False


# python字典排序 =============================
dict_demo = {"coins": 7, "pens": 3, "cups": 2, "bags": 1, "bottles": 4, "books": 5}

print("排序一:最简单的解决方案,以按键对数据进行排序")
sort_dict_demo = list(dict_demo.keys())
print("sort_dict_demo 的值为:" + str(sort_dict_demo))
# sort_dict_demo 的值为:['coins', 'pens', 'cups', 'bags', 'bottles', 'books']
sort_dict_demo.sort()
for k2 in sort_dict_demo:
    print(": ".join((k2, str(dict_demo[k2]))))

print("排序二:使用内置的sorted()功能可以完成更有效的分类——正序")
for k3 in sorted(dict_demo.keys()):
    print("{0}: {1}".format(k3, str(dict_demo[k3])))

print("排序三:使用内置的sorted()功能可以完成更有效的分类——倒序")
for k4 in sorted(dict_demo.keys(), reverse=True):
    print("{0}: {1}".format(k4, str(dict_demo[k4])))

print("排序四:使用内置的sorted()功能按照value的值排序,使用lambda匿名函数实现——正序")
for key1, value1 in sorted(dict_demo.items(), key=lambda pair: pair[1]):
    print("{0}: {1}".format(key1, value1))

print("排序五:使用内置的sorted()功能按照value的值排序,使用lambda匿名函数实现——倒序")
for key1, value1 in sorted(dict_demo.items(), key=lambda pair: pair[1], reverse=True):
    print("{0}: {1}".format(key1, value1))

Guess you like

Origin blog.csdn.net/m0_54701273/article/details/129405186