• 字典的用法


    一、如何定义字典。

    person_message ={

      'name':'zhangsan',  

      'age':21,

      'sex':'boy',

      'city':'shanxi'

    }

    print(person_message)

    执行结果:

    二、修改字典中的值。

    person_message ={

      'name':'王五',  

      'age':28,

      'sex':'boy',

      'city':'shanxi'

    }

    print(person_message)

     执行结果:

    三、增加字典中的值

    person_message ['hobby']='climb moutains'

    print(person_message)

    执行结果:

    四、访问字典中的值

    print(person_message['name'])

    执行结果:

    五、删除键-值对

    del(person_message['name'])

    print(person_message)

     执行结果:

    六、遍历字典

    1、遍历所有键-值对

    for key ,value in person_message.items():

      print(key,':',value)

    执行结果:

    2、遍历所有键

    for key in person_message.keys():

      print(key)

    执行结果:

    3、遍历所有的值

    for value in person_message.values():
    print(value)
    执行结果:

    4、按顺序遍历字典中的键

    for key in sorted(person_message.keys()):
    print(key)

    执行结果:

    七、嵌套

    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)

    执行结果:

    2、字典里嵌套列表

    favourite_numbers = {

    "Wangyang":['8','9','5'],

    "Fangmeng":['9'],

    "Baoxiao":['11'],

    }

    for name,numbers in favourite_numbers.items():

    print(name+':')

    for number in numbers:

    print(number)

    执行结果:

    3、字典嵌套字典

    cities = {
    'Chengdu': {
    'country': 'China',
    'population': '1390 million',
    'fact': 'so many people'
    },
    'Paris': {
    'country': 'French',
    'population': 'six-seven million',
    'fact': 'peple are very romantic'
    },
    'London': {
    'country': 'England',
    'population': '66 million',
    'fact': 'The men is very gentlemanly'
    }

    }

    for city, city_information in cities.items():
    print(' ' + city + ':')
    for city, value in city_information.items():
    print(city + ': ' + value)
    
    

     执行结果:

    在任何时候去学习都不晚,永远不要放弃自己!人生就是一个不断去学习的过程,任何时候,只要你想学,Come on !
  • 相关阅读:
    POJ 1306.Combinations
    HDU 5640.King's Cake
    HDU 1072.Nightmare
    HDU 2717.Catch That Cow
    HDU 1372.Knight Moves
    HDU 1548.A strange lift
    AOJ 802.运输宝物
    AOJ 794.西瓜理发记(二)
    AOJ 793.西瓜理发记(一)
    AOJ 789.买酒
  • 原文地址:https://www.cnblogs.com/startingpoint-fly/p/10643335.html
Copyright © 2020-2023  润新知