python基础-dict


# 理解字典后,你就能够更准确地为各种真实物体建模。
# 在Python中, 字典是一系列键—值对。字典用放在花括号{}中的一系列键—值对表示

# 1.一个简单的字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])

# 2.使用字典,可以将任何Python对象用作字典中的值。
# 2.1访问字典中的值:依次指定字典名和放在方括号内的键
print(alien_0['color']) 
# 2.2添加键-值对
alien_0['x_position'] = 0
alien_0['y_position'] = 1
print(alien_0)
# 2.3先创建一个空字典
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
# 2.4修改字典中的值:依次指定字典名、用方括号括起的键以及与该键相关联的新值。
alien_0['color'] = 'yellow'
print(alien_0)
# 2.5删除键-值对
del alien_0['points']  # 使用del语句时,必须指定字典名和要删除的键。
# 2.6由类似对象组成的字典
# 使用字典来存储众多对象的同一种信息
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
print(favorite_languages)
print(favorite_languages['jen'])
# P88动手试一试
# 6-1
person = {}
person['first_name'] = 'Ho'
person['last_name'] = 'Howard'
person['age'] = 26
person['city'] = 'Quanzhou'
print(person)
# 6-2
numbers = {
    'Jack': 1,
    'Rose': 2,
    'Mark': 3,
    'John': 4,
    'Mary': 5
}
print(numbers)
# 6-3
dictionary = {
    'if': 'logical cause',
    'while': 'loop cause',
    'in': 'includ cause',
    'print': 'output cause',
    'and': 'and'
}
print(dictionary)

# 3.遍历字典
# 3.1遍历所有的键-值对:方法items()
user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
}
for key, value in user_0.items(): # items返回一个键值对列表
    print('\nKey:' + key)
    print('Value:' + value)
print(user_0.items())
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is" + language.title())

# 3.2遍历字典中所有键:方法keys()
for name in favorite_languages.keys():
    print(name.title())
# 遍历字典时,会默认遍历所有的键
print('====')
for name in favorite_languages:
    print(name.title())
# 3.3按顺序遍历字典中的所有值:
# 获取字典的元素时,获取顺序是不可预测的;可以用sorted对keys排序
print('======sorted keys')
for name in sorted(favorite_languages.keys()):
    print(name.title())
# 3.4遍历字典中所有值,方法values()
print('==========values')
for language in favorite_languages.values():
    print(language)
# 种做法提取字典中所有的值,而没有考虑是否重复
# 剔除重复项,可使用集合(set)
# 集合类似于列表,但每个元素都必须是独一无二的:
print('=======set去重')
for language in set(favorite_languages.values()):
    print(language)
# 92动手试一试
# 6-4
for key, value in dictionary.items():
    print('\n' + key + ": " + value)
dictionary['else'] = 'logical cause'
dictionary['for'] = 'loop cause'
dictionary['set'] = 'set cause'
dictionary['list'] = 'list'
dictionary['dict'] = 'dict'
for key, value in dictionary.items():
    print('\n' + key + ": " + value)
# 6-5
rivers = {
    'nile': 'egypt',
    'Yangtze': 'china',
    'Ganges': 'india'
}
for river, country in rivers.items():
    print('The %s runs through %s' % (river, country))
for river in rivers.keys():
    print(river)
for country in rivers.values():
    print(country)
# 4.嵌套, 列表和字典的嵌套层级不应太多。
# 有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。
# 4.1字典列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
    print(alien)

# 4.2在字典中存储列表
favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
    print(name.title() + "'s favorite language are:")
    for language in languages:
        print(language)
# 4.3在字典中存储字典,代码可能很快复杂起来
users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
    },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
    },
}
for username, userinfo in users.items():
    print('\tUsername:' + username)
    full_name= userinfo['first'] + " " + userinfo['last'] 
    location = userinfo['location']
    print('\tFull_name: ' + full_name)
    print('\tLocation: ' + location)

# P99动手试一试
# 6-7
person_1 = {
    'name': 'jack',
    'job': 'teacher',
    'age': 30
}
person_2 = {
    'name': 'bob',
    'job': 'enginner',
    'age': 28
}
people = [person_1, person_2]
for person in people:
    print(person)
# 6-8
pet1 = {
    'type': 'dog',
    'host': 'jack'
}
pet2 = {
    'type': 'dog',
    'host': 'jack'
}
pets = [pet1, pet2]
for pet in pets:
    print(pet)
# 6-9
favorite_places = {
    'jack': ['Beijing', 'Xian'],
    'bob': ['Nanchang'],
    'lucy': ['Quanzhou', 'Hangzhou','Shanghai']
}
for name, places in favorite_places.items():
    print('\t%s likes these places,' % name)
    for place in places:
        print(place)
# 6-10
favorite_numbers = {
    'jack': [1,2,3],
    'bob': [6, 7, 1],
    'lucy': [0, 11, 34]
}
for name, numbers in favorite_numbers.items():
    print('\t%s likes these numbers,' % name)
    for num in numbers:
        print(num)
# 6-11
cities = {
    'Quanzhou': {
        'country': 'china',
        'population': '2000w',
        'fact': 'Beautiful'
    },
    'Londom': {
        'country': 'England',
        'population': '1000w',
        'fact': 'Rich'
    },
    'Tokoyo': {
        'country': 'Japan',
        'population': '3000w',
        'fact': 'Diff'
    },
}
for name, cityinfo in cities.items():
    print('\t' + name)
    for key, value in cityinfo.items():
        print(key + ": " + value)


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值