[英]From List of Dictionary To Dictionary
I have some problem with my function. 我的功能有问题。
I do an SQL Query to obtain a list that have some dictionary with only a key/value element. 我执行SQL查询以获取具有仅包含键/值元素的某些字典的列表。 This is a sample of my output:
这是我的输出的示例:
myDictList = [{'id': 55, 'sigla': 'SNG'}, {'id': 62, 'sigla': 'TRP'},
{'id': 71, 'sigla': 'PCNIM'}, {'id': 72, 'sigla': 'pc2ni'},
{'id': 73, 'sigla': 'ccas'}, {'id': 74, 'sigla': 'ased1'},
{'id': 75, 'sigla': '131s'}, {'id': 76, 'sigla': 'r888'},
{'id': 56, 'sigla': 'DBL'}]
The id
are unique (for SQL constraint). id
是唯一的(用于SQL约束)。
I've build a list of id
in that way 我以这种方式建立了一个
id
列表
r_id_list = list(rid['id'] for rid in roomList)
Now, i would build a dict. 现在,我要建立一个字典。 like that from
myDictList
: 像从
myDictList
:
{55:'SNG',62:'TRP',71:'PCNIM'.... and so on}
More over, i want to avoid part of code like that: 而且,我想避免这样的部分代码:
finalDict = {}
for element in myDictList:
finalDict.update({element['id']:element['sigla']})
I want to do that for some reasons: 由于某些原因,我想这样做:
sigla
value from r_id_list
element r_id_list
元素检索sigla
值 Some suggestion for a compact code that will not include a for
cycle inside a for
cycle, and increase the complexity? 关于紧凑代码的一些建议,该代码在
for
循环内不包含for
循环,并且会增加复杂性?
finalDict = dict([(k['id'], k['sigla']) for k in myDictList])
EDIT1 As comment mentioned, it will be a better way to do. EDIT1正如评论所述,这将是一个更好的方法。
finalDict = dict(((k['id'], k['sigla']) for k in myDictList))
EDIT2 编辑2
finalDict = dict((k['id'], k['sigla']) for k in myDictList)
将dict()构造函数与生成器表达式一起使用:
finalDict = dict((elem['id'], elem['sigla']) for elem in myDictList)
finaldict = {k['id']: k['sigla'] for k in myDictList}
if you're on a current version of Python. 如果您使用的是最新版本的Python。 Dictionary comprehensions have been introduced in Python 3 and backported to Python 2.7:
字典理解已在Python 3中引入,并反向移植到Python 2.7:
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> myDictList = [{'id': 55, 'sigla': 'SNG'}, {'id': 62, 'sigla': 'TRP'},
... {'id': 71, 'sigla': 'PCNIM'}, {'id': 72, 'sigla': 'pc2ni'},
... {'id': 73, 'sigla': 'ccas'}, {'id': 74, 'sigla': 'ased1'},
... {'id': 75, 'sigla': '131s'}, {'id': 76, 'sigla': 'r888'},
... {'id': 56, 'sigla': 'DBL'}]
>>> {k['id']: k['sigla'] for k in myDictList}
{71: 'PCNIM', 72: 'pc2ni', 73: 'ccas', 74: 'ased1', 75: '131s', 76: 'r888', 55:'SNG', 56: 'DBL', 62: 'TRP'}
Consider taking a step back here and looking outside the narrow focus of the question. 考虑退后一步,在问题的狭focus范围之外寻找。 You say "I do an SQL Query to obtain a list that have some dictionary".
您说“我执行SQL查询以获取具有某些词典的列表”。 What are you using to do the SQL query?
您正在使用什么进行SQL查询?
By default Python database drivers return a tuple
for each row rather than dict
, so you presumably have some other code which is converting those tuples into a dict
before you want to convert them back again. 默认情况下,Python数据库驱动程序为每行而不是
dict
返回一个tuple
,因此,您大概还有其他代码将这些元组转换为dict
然后再将其转换回。 Your best bet would be to just do a query that returns tuples and construct your dict directly from that: 最好的选择就是执行一个返回元组的查询,并直接从中构造字典:
cursor.execute('SELECT id, sigla FROM sometable')
myDict = dict(cursor.fetchall())
res_dict = {}
for i in myDictList:
res_dict[i['id']] = i['sigla']
As others have already pointed out the best way to build your final dictionary is using a generator expression like: 正如其他人已经指出的那样,构建最终字典的最佳方法是使用生成器表达式,例如:
finalDict = dict((d['id'], d['sigla']) for d in myDictList)
And if you still need an iterable over your ids you can have that just calling finalDict.keys()
. 如果您仍然需要对ID进行迭代,则可以只调用
finalDict.keys()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.