[英]Is this the fastest way to build dict?
I am reading an element list from an xml
file and make the data into 2 dictionaries. 我正在从
xml
文件中读取元素列表,并将数据制成2个字典。
Was this the fastest way? 这是最快的方法吗? (I don't think this is the best, you guys always surprise me.;-)
(我认为这不是最好的,你们总是让我感到惊讶。;-)
ADict = {}
BDict = {}
for x in fields:
key = x.get('key')
ADict[key] = x.find('A').text
BDict[key] = x.find('B').text
I think add it one by one is a bad idea, but write it in a single line. 我认为一个接一个地添加它是一个坏主意,但是请一行编写。 aka more pythonic way like this
又名像这样的更多pythonic方式
ADict,BDict = [dict(k) for k in zip(*([(x.get('key'),x.find('A').text),(x.get('key'),x.find('B').text)] for x in fields))]
I don't think it's better, two reasons, first, x.get('key')
was called twice second, create too much temp tuples 我认为这不是更好,这有两个原因,首先,
x.get('key')
被调用了两次,创建了过多的临时元组
Not tested, but should work 未经测试,但应该可以
ADict = dict((x.get('key'), x.find('A').text) for x in fields)
BDict = dict((x.get('key'), x.find('B').text) for x in fields)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.