美文网首页python
python(7):字典(2)

python(7):字典(2)

作者: Z_bioinfo | 来源:发表于2022-03-29 19:19 被阅读0次

    1.嵌套

    将一系列字典存贮再列表中,或将列表作为值存贮在字典中,称为嵌套。可以在列表中嵌套字典,字典中嵌套列表,字典中嵌套字典。

    #在列表中存贮字典
    dict1 = {'age': 18 , 'height': 175}
    dict2 = {'name': 'xiaoming' , 'weight': 130}
    dict3 = {'hair': 'black' , 'eye': 'black'}
    d = [dict1, dict2, dict3]
    for i in d:
        print(i)
    {'age': 18, 'height': 175}
    {'name': 'xiaoming', 'weight': 130}
    {'hair': 'black', 'eye': 'black'}
    =========================================
    #在字典中存贮列表
    pizza = {
        'crust': 'thick',
        'toppings': ['mushrooms', 'extra cheese']
    }
    print("you ordered a " + pizza['crust'] + '-crust pizza ' + 'with the following toppings:')
    for topping in pizza['toppings']:
        print('\t' + topping)
    you ordered a thick-crust pizza with the following toppings:
        mushrooms
        extra cheese
    favorite_languages = {
        'jen': ['python', 'ruby'],
        'sarach':['c'],
        'edward':['ruby', 'go'],
        'phil':['python', 'c++'],
    }
    for name,languages in favorite_languages.items():
        print('\n' + name + ' favorite language are:')
        for language in languages:
            print('\t'+ language)
    jen favorite language are:
        python
        ruby
    
    sarach favorite language are:
        c
    
    edward favorite language are:
        ruby
        go
    
    phil favorite language are:
        python
        c++
    ========================
    #字典中存贮字典
    #首先定义一个名为users的字典,其中包含两个键:用户名'aeinstein'和'mcurie',与每个键相关联的值都是一个字典,其中包含用户的名,姓,居住地
    users = {
        'aeinstein':{
            'first': 'albert',
            'last': 'einstein',
            'location': 'princeton',
        },
        'mcurie':{
            'first': 'marie',
            'last': 'curie',
            'location': 'paris',   
        },
    }
    for username,user_info in users.items():#遍历字典users,让python依次将每个键存贮在变量username中,并依次将与当前键相关联的字典存贮在变量user_info中
        print('\nusername: ' + username)#打印用户名
        full_name = user_info['first'] + " " + user_info['last']#访问内部字典,变量user_info包含用户信息字典,而该字典包含三个键:'first','last','location'
        location = user_info['location']
        print('\tfull_name: ' + full_name)
        print('\tlocation: ' + location)
    username: aeinstein
        full_name: albert einstein
        location: princeton
    
    username: mcurie
        full_name: marie curie
        location: paris

    相关文章

      网友评论

        本文标题:python(7):字典(2)

        本文链接:https://www.haomeiwen.com/subject/vyqbjrtx.html