zoukankan      html  css  js  c++  java
  • 将字典键和值拆分为单独的列表

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

    方法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']
  • 相关阅读:
    今天一天看一天文档
    ImportError: No module named _md5解决方案
    Spelling Corrector & sphinx typo search
    linux下使用ipython的pylab模式时不显示图形的问题解决方案
    error: error in setup script: command 'build_exe' has no such option 'includefiles'
    【转】oracle之包的创建和应用
    ADO.NET 与 ORACLE
    SQL注入大全
    【转】oracle之循环语法
    ASP.NET 防止按钮多次提交解决方法
  • 原文地址:https://www.cnblogs.com/a00ium/p/13859014.html
Copyright © 2011-2022 走看看