python 將列表里的字典元素合并為一個字典實例
更新時間:2020年09月01日 10:13:12 作者:cw-Austin
這篇文章主要介紹了python 將列表里的字典元素合并為一個字典實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
我就廢話不多說了,大家還是直接看代碼吧~
def list_dict(list_data):
dict_data = {}
for i in list_data:
key, = i
value, = i.values()
dict_data[key] = value
return dict_data
if __name__ == '__main__':
list_data = [{'aa': 'aa'},
{'bb': 'bb'},
{'cc': 'cc'},
{'dd': 'dd'}]
print list_dict(list_data)
返回結(jié)果:
{'aa': 'aa', 'cc': 'cc', 'dd': 'dd', 'bb': 'bb'}
補(bǔ)充知識:python操作excel,將每行信息放在字典里,所有信息放在一個列表里
實例如下:
#coding=utf8
from selenium import webdriver
import xlrd,os
dirname = os.path.dirname(os.path.dirname(__file__))
#join時,第二參數(shù)首位不能加/,加r的意思是原生字符串
filename = os.path.join(dirname,r'testdata/select_school.xlsx')
#row,col獲取哪行那列的值
def run_select_shool(row=1,col=1):
#打開excel文件讀取數(shù)據(jù)
data = xlrd.open_workbook(filename)
table = data.sheet_by_index(0)
row = row-1
col = col-1
#獲取整行整列的值
nrows = table.row_values(row)
ncols = table.col_values(0)
print(nrows[col])
def run_select_school2(filename,sheet_index=0,table_header_row=0):
# 打開excel文件讀取數(shù)據(jù)
data = xlrd.open_workbook(filename)
table = data.sheet_by_index(sheet_index)
nrows = table.nrows
nclos = table.ncols
#獲取表頭行的信息,為一個列表
header_row_data = table.row_values(table_header_row)
#將每行的信息放入一個字典,再將字典放入一個列表中
list = []
for rownum in range(1,nrows):
rowdata = table.row_values(rownum)
#如果rowdata有值,
if rowdata:
dict = {}
for j in range(0,len(header_row_data)):
#將excel中的數(shù)據(jù)分別設(shè)置成鍵值對的形式,放入字典,如‘標(biāo)題':‘name';
dict[header_row_data[j]] = rowdata[j]
list.append(dict)
print(list)
return list
run_select_school2(filename)
以上這篇python 將列表里的字典元素合并為一個字典實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python三種數(shù)據(jù)結(jié)構(gòu)及13種創(chuàng)建方法總結(jié)
拿Python來說,數(shù)據(jù)結(jié)構(gòu)的概念也是超級重要,不同的數(shù)據(jù)結(jié)構(gòu),有著不同的函數(shù),供我們調(diào)用,接下來,我們分別來介紹字符串、列表、字典的創(chuàng)建方法2021-09-09
python 中的list和array的不同之處及轉(zhuǎn)換問題
python中的list是python的內(nèi)置數(shù)據(jù)類型,list中的數(shù)據(jù)類不必相同的,而array的中的類型必須全部相同。這篇文章給大家介紹了python 中的list和array的不同之處及轉(zhuǎn)換問題,需要的朋友參考下吧2018-03-03

