美文网首页
Python:嵌套

Python:嵌套

作者: 庭阶 | 来源:发表于2020-04-15 13:20 被阅读0次

1.在列表中嵌套字典

字典列表:将字典存储在列表中

alien_0={
    'color':'green',
    'points':5
    }
alien_1={
    'color':'yellow',
    'points':15
    }
alien_2={
    'color':'black',
    'points':10
    }
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)

2.在字典中嵌套列表

将列表存储在字典中
每当需要在字典中讲一个键关联到多个值时,都可以在字典中嵌套一个列表

favorite_languages={
    'jen':['python','ruby'],
    #或者'sarah':'c';
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
    }
for name,languages in favorite_languages.items():
    if len(languages)>1:
        print("\n"+name.title()+"'s favorite language are:")
        for language in languages:
            print("\t"+language.title())
    else:
        print("\n"+name.title()+"'s favorite language is:")
        for language in languages:
            print("\t"+language.title())

3.字典中嵌套字典

在字典中存储列表

一般字典中的结构最好相同,处理比较容易,如果键不同,可能处理更复杂

users={
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton'
        },
    'mcurie':{
         'first':'marie',
        'last':'curie',
        'location':'paris'
        }
    }
for username,user_info in users.items():
    print("\nusername:"+username)
    full_name=user_info['first']+" "+user_info['last']
    location=user_info['location']
    print("\tfullname:"+full_name.title())
    print("\tlocation:"+location.title())

相关文章

  • python新手任务:python循环嵌套

    Python 循环嵌套 Python 语言允许在一个循环体里面嵌入另一个循环。 Python for 循环嵌套语法...

  • Python基础-08数据嵌套

    8.数据嵌套     在Python中,各种数据是可以相互嵌套的,如列表中嵌套元组、整型、字典等,字典中也可以嵌套...

  • 14-Python循环和分支的互相嵌套

    1.循环内嵌套if 2.循环内嵌套循环 学习地址: 撩课-Python大数据+人工智能1撩课-Python大数据+...

  • Python:嵌套

    1.在列表中嵌套字典 字典列表:将字典存储在列表中 2.在字典中嵌套列表 将列表存储在字典中每当需要在字典中讲一个...

  • 8、Python列表

    上集回顾: Python函数 while循环嵌套 Python列表(list)是一种有序的集合,是 Python ...

  • 列表,字典排序

    列表嵌套字典,根据字典某一key排序python sort、sorted高级排序技巧(key的使用)Python要...

  • Python3 函数嵌套

    在Python中会经常使用函数嵌套,那么我们来看下什么是函数嵌套。 我们知道单个函数的形式: def print_...

  • python

    1/python requests post嵌套键值对数组 1/header 2/json.dumps

  • python处理文字,读取execl表格入库

    python读取嵌套字典 eval str---->dict 列表去掉{} https://www.php.cn...

  • Python list 生成式(推导式list comprehe

    在list生成式中嵌套if else 如果按中文习惯写嵌套列表生成式可能写出如下的错误语法 Python的语法是按...

网友评论

      本文标题:Python:嵌套

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