• 将字典键和值拆分为单独的列表


    给定字典,任务是将该字典拆分为键,并将值拆分为不同的列表。让我们讨论执行此操作的不同方法。

    方法1:使用 built-in functions

    # Python code to demonstrate
    # to split dictionary
    # into keys and values
    
    # initialising _dictionary
    ini_dict = {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'}
    
    # printing iniial_dictionary
    print("intial_dictionary", str(ini_dict))
    
    # split dictionary into keys and values
    keys = ini_dict.keys()
    values = ini_dict.values()
    
    # printing keys and values separately
    print("keys : ", str(keys))
    print("values : ", str(values))

    输出:

    intial_dictionary {'a':'akshat','b':'bhuvan','c':'chandan'}
    键:dict_keys(['a','b','c']) 值:dict_values(['akshat','bhuvan','chandan'])

     
    方法2:使用 zip()

    # Python code to demonstrate
    # to split dictionary
    # into keys and values
    
    # initialising _dictionary
    ini_dict = {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'}
    
    # printing iniial_dictionary
    print("intial_dictionary", str(ini_dict))
    
    # split dictionary into keys and values
    keys, values = zip(*ini_dict.items())
    
    # printing keys and values separately
    print("keys : ", str(keys))
    print("values : ", str(values))

    输出:
    intial_dictionary {'a':'akshat','c':'chandan','b':'bhuvan'}
    键:('a','c','b')
    值:(“ akshat”,“ chandan”,“ bhuvan”)
    

     
    方法#3:使用 items()

    # Python code to demonstrate
    # to split dictionary
    # into keys and values
    
    # initialising _dictionary
    ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
    
    # printing iniial_dictionary
    print("intial_dictionary", str(ini_dict))
    
    # split dictionary into keys and values
    keys = []
    values = []
    items = ini_dict.items()
    for item in items:
        keys.append(item[0]), values.append(item[1])
    
    # printing keys and values separately
    print ("keys : ", str(keys))
    print ("values : ", str(values))
    出:
    intial_dictionary {'b':'bhuvan','c':'chandan','a':'akshat'}
    键:['b','c','a']
    值:['bhuvan','chandan','akshat']
  • 相关阅读:
    django 常用命令
    nginx+gunicorn
    终于决定写个技术博客
    test
    自定义控件
    .net mvc 发布部署到机器上
    C# StringExt 字符串扩展
    MYSQL连接数据库
    List IEnumerable
    CentOS安装pip
  • 原文地址:https://www.cnblogs.com/a00ium/p/13859014.html
Copyright © 2020-2023  润新知