欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python中字典的那些事(1)

程序员文章站 2022-05-04 19:44:45
...

python中的字典那些事

python中字典的那些事(1)

我观看bilibili的视频,并总结了一些字典的知识,希望能帮到大家。

1.1一个简单的字典

创建一个空字典

people={}

添加键值对后的字典

# create a dictionnary
people={'first_name':'jignqin',
        'last_name':'mo',
        'city':'zhanjiag',
        'age':'7'
        }

1.2 使用字典

1.2.1访问字典中的值

print (people['first_name'])
print (people['last_name'])
print (people['city'])
print (people['age'])

1.2.2添加键-值对

people['hobby']='football'

1.2.3修改字典中的值

people['age']=8

1.2.4 删除键-值对(del)

del people['city']

1.3遍历字典

1.3.1 遍历所有的键-值对(items)

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

1.3.2 遍历字典中的所有键(keys)

for name in people.keys():
    print(name)

1.3.3 按顺序遍历字典中的所有键(sorted)

for name in sorted(people.keys()):
    print(name)

1.3.4 遍历字典中所有的值(values)

for v in people.values():
    print(v)

1.4 嵌套

1.4.1 字典列表(列表中包含字典)

# Make an empty list to store people in.
people = []

# Define some people, and add them to the list.
person = {
    'first_name': 'eric',
    'last_name': 'matthes',
    'age': 43,
    'city': 'sitka',
    }
people.append(person)

person = {
    'first_name': 'ever',
    'last_name': 'matthes',
    'age': 5,
    'city': 'sitka',
    }
people.append(person)

person = {
    'first_name': 'willie',
    'last_name': 'matthes',
    'age': 8,
    'city': 'sitka',
    }
people.append(person)

1.4.2 字典中存储列表

favorite_numbers = {
    'mandy': [42, 17],
    'micah': [42, 39, 56],
    'gus': [7, 12],
    }

for name, numbers in favorite_numbers.items():
    print("\n" + name.title() + " likes the following numbers:")
    for number in numbers:
        print("  " + str(number))

1.4.3 字典中存储字典

cities = {
    'santiago': {
        'country': 'chile',
        'population': 6158080,
        'nearby mountains': 'andes',
        },
    'talkeetna': {
        'country': 'alaska',
        'population': 876,
        'nearby mountains': 'alaska range',
        },
    'kathmandu': {
        'country': 'nepal',
        'population': 1003285,
        'nearby mountains': 'himilaya',
        }
    }

for city, city_info in cities.items():
    country = city_info['country'].title()
    population = city_info['population']
    mountains = city_info['nearby mountains'].title()

    print("\n" + city.title() + " is in " + country + ".")
    print("  It has a population of about " + str(population) + ".")
    print("  The " + mountains + " mountains are nearby.")

参考

习题