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 = [, , ]
sorted(symbol_arr, key=lambda s:s.amount, reverse=true)

希望本文所述对大家python程序设计有所帮助。

Posted in 未分类

发表评论