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']
  • 相关阅读:
    ubuntu 搜索文件方法(find命令)
    tomcat ip访问
    Linux下tomcat 的启动 关闭 kill
    Hibernate 之 使用
    tar 用法
    ubuntu下配置django+apache+mysql+mod_python+Python
    Windows Mobile Ping 命令实现(转)
    C#异步方法调用(四大方法详解)
    HTML基础(一):HTML简介
    windows2003系统的iis不能下载exe文件
  • 原文地址:https://www.cnblogs.com/a00ium/p/13859014.html
Copyright © 2011-2022 走看看