Python 将具有相同键的dict组合成一个具有列表的dict
我有一个dicts元组,它是我从mysql服务器收到的答案Python 将具有相同键的dict组合成一个具有列表的dict,python,dictionary,Python,Dictionary,我有一个dicts元组,它是我从mysql服务器收到的答案 ({ 'firstname': 'Alexandro', 'Title': 'My life', 'lastname': 'Riviera', 'articles.id': 6L, 'authorId': 1L, 'id': 1L }, { 'firstname': 'Alexandro', 'Title': 'My life 2', 'lastname': 'Ri
({
'firstname': 'Alexandro',
'Title': 'My life',
'lastname': 'Riviera',
'articles.id': 6L,
'authorId': 1L,
'id': 1L
}, {
'firstname': 'Alexandro',
'Title': 'My life 2',
'lastname': 'Riviera',
'articles.id': 7L,
'authorId': 1L,
'id': 1L
}, {
'firstname': 'Helen',
'Title': 'Learn SQL',
'lastname': 'Oldgarno',
'articles.id': 8L,
'authorId': 2L,
'id': 2L
}, {
'firstname': 'Helen',
'Title': 'SQL for you',
'lastname': 'Oldgarno',
'articles.id': 9L,
'authorId': 2L,
'id': 2L
})
我想通过相同的键将“authorId”转换为:
我不知道如何以一种不太丑陋的方式完成这项任务。任何建议都会有帮助 您可以将其转换为列表并按authord排序。一旦你能够根据AuthID将它们分开,你就可以将作者信息字段折叠起来,并将文章信息放进列表中。
你可以编写这样的合并函数,但是你确实应该考虑改写SQL查询。以下是一个简单的解决方案:
def merge_books(books):
merged = {}
for book in books:
authorId = book['authorId']
# Create article attribute
book['articles'] = [{
'articles.id': book['articles.id'],
'authorId': book['authorId'],
'Title': book['Title'],
}]
# Remove redundant information
del book['articles.id']
del book['authorId']
del book['Title']
if authorId in merged:
merged[authorId]['articles'].append(book['articles'][0])
else:
merged[authorId] = book
# Convert dict into a tuple, but why not a list?
return tuple(merged.values())
更好的方法是使用两个select语句并将其结果合并在一起:
import MySQLdb
def get_authors_with_articles(connection):
cursor = connection.cursor()
authors = {}
for author in cursor.execute('SELECT * FROM Authors'):
# Initialize empty article list that will be popluated with the next select
author['articles'] = []
authors[author['id']] = author
for article in cursor.execute('SELECT * FROM Articles').fetchall():
# Fetch and delete redundant information
author_id = article['authorId']
del article['authorId']
authors[author_id]['articles'].append(article)
return list(authors.values())
if __name__ == '__main__':
connection = MySQLdb.connect(
mysql_host,
mysql_user,
mysql_pass,
mysql_base,
cursorclass=MySQLdb.cursors.DictCursor
)
print(get_authors_with_articles(connection))
也许这个问题(及其答案)会有所帮助:这就是我为什么要问的原因。我的SQL查询很简单:)
import MySQLdb
def get_authors_with_articles(connection):
cursor = connection.cursor()
authors = {}
for author in cursor.execute('SELECT * FROM Authors'):
# Initialize empty article list that will be popluated with the next select
author['articles'] = []
authors[author['id']] = author
for article in cursor.execute('SELECT * FROM Articles').fetchall():
# Fetch and delete redundant information
author_id = article['authorId']
del article['authorId']
authors[author_id]['articles'].append(article)
return list(authors.values())
if __name__ == '__main__':
connection = MySQLdb.connect(
mysql_host,
mysql_user,
mysql_pass,
mysql_base,
cursorclass=MySQLdb.cursors.DictCursor
)
print(get_authors_with_articles(connection))