码迷,mamicode.com
首页 > 其他好文 > 详细

列表转换成字典数据结构

时间:2015-01-12 18:48:29      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

‘‘‘
[
    {‘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)

 

列表转换成字典数据结构

标签:

原文地址:http://www.cnblogs.com/linjiqin/p/4218940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!