Python Dictionaries

本文介绍了Python中字典的基本操作,包括获取长度、增删改查等,并通过具体示例展示了如何使用字典的方法如get、clear等进行高效的数据管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

dict函数


 

基本的字典操作

len(d)返回d中项(key-value)的数量

d[k]返回关联到键k上的值

d[k]=v将值v关联到键k上

del d[k]删除键为k的项

k in d检查d中是否有含有键为k的项

 

来看个简单的例子

databases = {
    "Oracle" : {
        "username" : "oracleapp",
        "password" : "oracleapp123"
    },

    "Db2" : {
        "username" : "db2app",
        "password" : "db2app123"
    },

    "MongoDB" : {
        "username" : "mongodbapp",
        "password" : "mongodbapp123"
    }
}

labels = {
    "username" : "DB Username",
    "password" : "DB Password"
}

name = raw_input("DB Name : ")

request = raw_input("DB Username(u) or DB Password(p)? ")

if request == "u" : key = "username"
if request == "p" : key = "password"

if name in databases :
    print "%s database's %s is %s." % (name, labels[key], databases[name][key])

 运行结果如下所示:

 

字典的格式化字符串

 

字典方法:clear、copy、fromkeys、get



 

接下来改写上面那个代码,使用get方法来访问实体

databases = {
    "Oracle" : {
        "username" : "oracleapp",
        "password" : "oracleapp123"
    },

    "DB2" : {
        "username" : "db2app",
        "password" : "db2app123"
    },

    "MongoDB" : {
        "username" : "mongodbapp",
        "password" : "mongodbapp123"
    }
}

labels = {
    "username" : "DB Username",
    "password" : "DB Password"
}

name = raw_input("DB Name : ")

request = raw_input("DB Username(u) or DB Password(p)? ")


if request == "u" :
    key = "username"
elif request == "p" :
    key = "password"
else :
    key = request


db = databases.get(name, {})
label = labels.get(key, key)
result = db.get(key, "not available")


print "%s database's %s is %s." % (name, label, result)

运行结果如下所示:


 

has_key、items、iteritems、keys、iterkeys、values、itervalues



 

pop、popitem、setdefault、update




Summary


 

我想用Python代码将mat文件转成json文件,采用了如下代码import os import json import scipy.io as spio import pandas as pd def loadmat(filename): ''' this function should be called instead of direct spio.loadmat as it cures the problem of not properly recovering python dictionaries from mat files. It calls the function check keys to cure all entries which are still mat-objects ''' data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True) return _check_keys(data) def _check_keys(dict): ''' checks if entries in dictionary are mat-objects. If yes todict is called to change them to nested dictionaries ''' for key in dict: if isinstance(dict[key], spio.matlab.mio5_params.mat_struct): dict[key] = _todict(dict[key]) return dict def _todict(matobj): ''' A recursive function which constructs from matobjects nested dictionaries ''' dict = {} for strg in matobj._fieldnames: elem = matobj.__dict__[strg] if isinstance(elem, spio.matlab.mio5_params.mat_struct): dict[strg] = _todict(elem) else: dict[strg] = elem return dict def mat2json(mat_path=None, filepath = None): """ Converts .mat file to .json and writes new file Parameters ---------- mat_path: Str path/filename .mat存放路径 filepath: Str 如果需要保存成json, 添加这一路径. 否则不保存 Returns 返回转化的字典 ------- None Examples -------- >>> mat2json(blah blah) """ matlabFile = loadmat(mat_path) #pop all those dumb fields that don't let you jsonize file matlabFile.pop('__header__') matlabFile.pop('__version__') matlabFile.pop('__globals__') #jsonize the file - orientation is 'index' matlabFile = pd.Series(matlabFile).to_json() if filepath: json_path = os.path.splitext(os.path.split(mat_path)[1])[0] + '.json' with open(json_path, 'w') as f: f.write(matlabFile) return matlabFile 现在出现报错:DeprecationWarning: Please import 'mat_struct' from the 'scipy.io.matlab' namespace
最新发布
03-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值