学习笔记

FOR函数+列表+字典的处理

janice No Comments

两个简单的函数例子,处理列表和字典:

list1 = [{'field':'v1', 'key':'k1'},{'field':'v2', 'key':'k2'},{'field':'v3', 'key':'k3'} ]

dict1 = {'k1':100,'k2':200, 'k3':300}
dict2 =dict([(k['field'],dict1[k['key']]) for k in list1])
print(dict2)
result = [{'addr': '501', 'field': 'height_1'}]
result2 = {'height_1': '3.222'}

macro_dict =  dict([(k['addr'],result2[k['field']]) for k in result])
print(macro_dict)

以上两个例子也是for函数的简单运用。

字典按Key排序 转字符串

janice No Comments

普通字典默认是无序的,有序的字典需要用到OrderedDict:

简单例子如下:

import collections,json

json_send = {"Timeout": "10", "CNCFile": "O6666", "CNC": "CNC_3", 
"LocalFile": "E:\\xtec\\test\\TESTING",
"CNCPath": "//CNC_MEM/USER/PATH1/", "Command": "FTPSendFile"}

d1 = collections.OrderedDict()
for i in sorted(json_send): 
    d1[i] = json_send[i]
    print(d1)
print(json.dumps(d1))

分类目录

关于我

 Janice 詹

QQ   455899417

janice2014@foxmail.com