顯示具有 dict 標籤的文章。 顯示所有文章
顯示具有 dict 標籤的文章。 顯示所有文章

2017年11月20日 星期一

Python - Convert xml data to dict to in python - 將xml格式轉換為字典

版本

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Codes:

import xmltodict, json
xml_str = '<root><rule>a</rule><right>1</right></root>'
order_dict_tmp = xmltodict.parse(xml_str)
dict_temp = json.loads(json.dumps(order_dict_tmp))
print( xml_str )
print('-'*35)
print( order_dict_tmp )
print( type(order_dict_tmp) )
print('-'*35)
print( dict_temp )
print( type(dict_temp) )

執行結果:

2017年11月8日 星期三

Python - Convert a dict to XML in python - 將字典轉換為XML的格式

版本

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Codes:

# dict to xml
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import tostring
def dict_to_xml(tag, d):
    ele = Element(tag)
    for key, val in d.items():
        child = Element('key',{'name':key})
        child.text = str(val)
        ele.append(child)
    return ele

dic1 = {'a':5,'123b':22,'c':'str1'}
print(dic1)
print('-'*85)
xml_str = tostring(dict_to_xml('score', dic1)  )
xml_str2 = xml_str.decode()
print(xml_str2)
print('='*85)
xml_str = tostring(dict_to_xml('score', dic1), encoding='utf8', method='xml')
xml_str2 = xml_str.decode()
print(xml_str2)

執行結果:

2017年9月5日 星期二

Python - Convert String to list and Convert list to dictionary in Python - 字串藉由指定符號轉為list與list轉為字典

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10
str1 = '背景,0,特性,1,元件,3'
list1 = str1.split(",")
dic1 = {list1[i]: list1[i+1] for i in range(0, len(list1), 2)}
print(list1)
print(dic1)
執行結果:
['背景', '0', '特性', '1', '元件', '3']
{'背景': '0', '特性': '1', '元件': '3'}

2017年8月30日 星期三

Python - Pretty printing nested dictionaries - 印出巢狀結構的字典

Version:

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Code:

from pprint 
import pprint 
dic1 ={'name':'Dondonaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'number':9527,'item':['a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b']} 
print(dic1) 
print('='*30) 
pprint(dic1)

Result:


2017年7月27日 星期四

Python - Convert list to dictionary with indexes - 將list轉為字典且將index設為字典的key

Version

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Code:

list1 = ['A','B','C']
dic1 = {k:v for k,v in enumerate(list1)}
dic1

Result:

{0: 'A', 1: 'B', 2: 'C'}