ホームページ >バックエンド開発 >Python チュートリアル >Python实现列表转换成字典数据结构的方法
本文实例讲述了Python实现列表转换成字典数据结构的方法。分享给大家供大家参考,具体如下:
''' [ {'symbol': 101, 'sort': 1, 'name': 'aaaa'}, {'symbol': 102, 'sort': 2, 'name': 'bbbb'}, {'symbol': 103, 'sort': 3, 'name': 'cccc'}, {'symbol': 104, 'sort': 4, 'name': 'dddd'}, {'symbol': 105, 'sort': 5, 'name': 'eeee'}, {'symbol': 106, 'sort': 6, 'name': 'ffff'}, {'symbol': 107, 'sort': 7, 'name': 'gggg'}, {'symbol': 108, 'sort': 8, 'name': 'hhhh'}, {'symbol': 109, 'sort': 9, 'name': 'iiii'} ] 转换成如下的结构,便于通过ID获取记录值 { 101: {'sort': 1, 'symbol': 101, 'name': 'aaaa'}, 102: {'sort': 2, 'symbol': 102, 'name': 'bbbb'}, 103: {'sort': 3, 'symbol': 103, 'name': 'cccc'}, 104: {'sort': 4, 'symbol': 104, 'name': 'dddd'}, 105: {'sort': 5, 'symbol': 105, 'name': 'eeee'}, 106: {'sort': 6, 'symbol': 106, 'name': 'ffff'}, 107: {'sort': 7, 'symbol': 107, 'name': 'gggg'}, 108: {'sort': 8, 'symbol': 108, 'name': 'hhhh'}, 109: {'sort': 9, 'symbol': 109, 'name': 'iiii'} } ''' students = [ {'symbol': 101, 'sort': 1, 'name': 'aaaa'}, {'symbol': 102, 'sort': 2, 'name': 'bbbb'}, {'symbol': 103, 'sort': 3, 'name': 'cccc'}, {'symbol': 104, 'sort': 4, 'name': 'dddd'}, {'symbol': 105, 'sort': 5, 'name': 'eeee'}, {'symbol': 106, 'sort': 6, 'name': 'ffff'}, {'symbol': 107, 'sort': 7, 'name': 'gggg'}, {'symbol': 108, 'sort': 8, 'name': 'hhhh'}, {'symbol': 109, 'sort': 9, 'name': 'iiii'} ] symbol_list = map(lambda x: (x.get('symbol'), x), students) print symbol_list print '-----------------------------------------' print dict(symbol_list) #value_list = map(lambda x: x, students) # ##print dict(zip(symbol_list, value_list)) # # #student = { # 101: {'symbol': 101, 'sort': 1, 'name': 'aaaa'} # } # #student = [ # {101: {'symbol': 101, 'sort': 1, 'name': 'aaaa'}} # ] #
排序用法:
students = [ {'name':'zhangsan', 'price':20.01, 'date':'2015-01-09T01:00:00Z'}, {'name':'lisi', 'price':10.01, 'date':'2013-01-09T01:00:00Z'}, {'name':'wangwu', 'price':0.01, 'date':'2012-01-09T01:00:00Z'} ] print sorted(students, key=lambda s:s["name"]) print sorted(students, key=lambda s:s["price"], reverse=True) print sorted(students, key=lambda s:s["date"], reverse=True) aa = sorted(students, key=lambda s:s["price"], reverse=True) sorted(aa, key=lambda s:s["date"], reverse=True) symbol_arr = [<Symbol: Symbol object>, <Symbol: Symbol object>, <Symbol: Symbol object>] sorted(symbol_arr, key=lambda s:s.amount, reverse=True)
希望本文所述对大家Python程序设计有所帮助。