如何从python字典中删除多余的键

时间:2019-02-03 09:04:02

标签: python dictionary

我想从输出中删除多余的键,但不确定如何删除。

附加键 ('DiskStatus', {'DiskStatus':[

期望键 ('DiskStatus': [

test.csv

test.csv
/,9.8G,6.8G,27%
/home,4.8G,3.6G,22%
/opt,9.8G,5.2G,44%
/tmp,3.9G,3.6G,2%

代码

import csv
from collections import OrderedDict
import collections
import socket
type = 'STATUS'
hostname =  socket.gethostname()
hotst = {}.fromkeys(['ServerName'],hostname)
type = {}.fromkeys(['type'],type)
disk_status = {'DiskStatus': []}
header = ['Mount', 'Total', 'available', 'used']
with open('test.csv') as infile:
    reader = csv.reader(infile)
    for line in reader:
        #updated line
        disk_status["DiskStatus"].append(collections.OrderedDict(zip(header, line)))

status = dict(hotst.items() + type.items())
order = collections.OrderedDict(status)
new_dict = collections.OrderedDict()
new_dict["ServerName"]=status["ServerName"]
new_dict["type"]=status["type"]
new_dict["DiskStatus"]=disk_status
print new_dict

代码输出

OrderedDict([('ServerName', 'dlccwsdigdsu03'), ('type', 'STATUS'), ('DiskStatus', {'DiskStatus': [OrderedDict([('Mount', '/'), ('Total', '9.8G'), ('available', '6.8G'), ('used', '27%')]), OrderedDict([('Mount', '/home'), ('Total', '4.8G'), ('available', '3.6G'), ('used', '22%')]), OrderedDict([('Mount', '/opt'), ('Total', '9.8G'), ('available', '5.2G'), ('used', '44%')]), OrderedDict([('Mount', '/tmp'), ('Total', '3.9G'), ('available', '3.6G'), ('used', '2%')])]})])

预期产量

OrderedDict([('ServerName', 'dlccwsdigdsu03'), ('type', 'STATUS'), ('DiskStatus': [OrderedDict([('Mount', '/'), ('Total', '9.8G'), ('available', '6.8G'), ('used', '27%')]), OrderedDict([('Mount', '/home'), ('Total', '4.8G'), ('available', '3.6G'), ('used', '22%')]), OrderedDict([('Mount', '/opt'), ('Total', '9.8G'), ('available', '5.2G'), ('used', '44%')]), OrderedDict([('Mount', '/tmp'), ('Total', '3.9G'), ('available', '3.6G'), ('used', '2%')])]})])

1 个答案:

答案 0 :(得分:2)

假设您希望使用('DiskStatus', [...])而不是('DiskStatus': [...])(逗号与冒号,后者在Python中是无效语法),则可以从原始字典中取出值:

new_dict["DiskStatus"] = disk_status["DiskStatus"]