我有一个字典列表,我有随机键:值对。我还有一个列表 - 我想将字段写入csv文件的顺序(字典的Essentialy键)。我使用下面的代码编写csv文件。
b,d,a,c
2,3,,
最终的CSV文件按顺序包含密钥:
Sub subFindScrollIE()
Dim boolFound As Boolean
Dim ie As InternetExplorer
Set ie = New InternetExplorer
ie.Navigate "my URL HERE"
strTemp = "KEYWORD1"
Do Until ie.ReadyState = READYSTATE_COMPLETE
'DoEvents
Loop
ie.Visible = True
Set txt = ie.Document.body.createTextRange()
boolFound = txt.findText(strTemp)
txt.moveStart "character", -1
txt.findText strTemp
txt.Select
txt.ScrollIntoView
Set ie = Nothing
End Sub
但是我想根据订单清单。我怎么能这样做?
答案 0 :(得分:3)
此代码段会产生您想要的输出
lst=[{"b":2,"d":3},{"a":1,"b":1,"c":5},{"d":7,"c":1}]
order = ["a","b","c","d"]
with open('file.csv', 'w') as output_file:
dict_writer = csv.DictWriter(output_file, order)
dict_writer.writeheader()
dict_writer.writerows(lst)
答案 1 :(得分:1)
您从未使用...
tabPanel("plot",
tagList(
tags$head(
tags$style(
".leaflet .legend {width:200px; text-align: left;}",
".leaflet .legend i{float: left;}",
".leaflet .legend label{float:left; text-align: left;}"
)
)
),
leafletOutput("leaflet_plot", width = 800, height = 550)
)
...
# code to create leaflet
output$leaflet_plot <- renderLeaflet({
pal <- c("#F1F1F1", brewer.pal(5, "YlOrBr"))
opts <- providerTileOptions(opacity = 0)
map <- leaflet(shape_file) %>% addProviderTiles("CartoDB.PositronNoLabels", options = opts)
map <- map %>% addPolygons(fillColor = ~colorFactor(pal, shape_file$var)(var)
map <- map %>% addLegend("bottomleft", title = "Employment/Acre", pal = colorFactor(pal, NULL), values = ~var)
map
})
。在创建DictWriter时,只需传递而不是{{1}}。
答案 2 :(得分:0)
首先从dict列表中获取所有键 第二种是基于您的订单列表的键列表 final根据排序的密钥写入标题
lst = [{'b': 2, 'd': 3}, {'a': 1, 'c': 5, 'b': 1}, {'c': 1, 'd': 7}]
flatLst = set([ k for ele in lst for k in ele.keys()])
def sortKey(x):
return order.index(x) if x in order else len(order)
orderedHeader = sorted( flatLst, key = lambda x:sortKey(x))
with open(filePath,'wb') as f:
w = csv.DictWriter(f,orderedHeader)
w.writeheader()
w.writerows(lst)
输出:
a b c d
2 3
1 1 5
1 7