V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ruoran
V2EX  ›  Python

Python有没有默认sort by key的dict?

  •  
  •   ruoran · 2013-05-16 06:12:43 +08:00 · 5148 次点击
    这是一个创建于 3969 天前的主题,其中的信息可能已经有所发展或是发生改变。
    就是像Java TreeMap那样用红黑树实现的东西?
    collection.OrderedDict是维持insert先后的顺序,不是我想问的那种。
    主要是想用一个call来取第n大的数据。
    10 条回复    1970-01-01 08:00:00 +08:00
    Hualin
        1
    Hualin  
       2013-05-16 09:04:36 +08:00   ❤️ 1
    keys = sorted(block_info.__dict__.keys())
    for key in keys:
    sort_block_info.append([key, getattr(block_info, key)])

    不知道这段代码对你没用。前提是你的 dict 的 key 命名的字母序是有意义的。比如叫 field1 field2...
    SErHo
        2
    SErHo  
       2013-05-16 09:11:00 +08:00   ❤️ 2
    yegle
        3
    yegle  
       2013-05-20 02:56:24 +08:00   ❤️ 1
    Livid
        4
    Livid  
    MOD
       2013-05-20 03:19:47 +08:00   ❤️ 1
    monkeylyf
        5
    monkeylyf  
       2013-05-20 03:31:43 +08:00
    OrderedDict + 1
    hhrmatata
        6
    hhrmatata  
       2013-05-20 09:19:29 +08:00
    python 2.7+支持collections.OrderedDict
    ruoran
        7
    ruoran  
    OP
       2013-05-20 09:26:50 +08:00
    @Hualin @SErHo @Livid @yegle @monkeylyf 谢谢!OrderedDict是可以满足需求,但是感觉@Livid说的这个更能解决根本需求 http://www.redis.io/commands/zadd 这个看上去在add时就已经排序了,而且logn。不太想每次get都要排序一下那种,nlogn。
    DH
        8
    DH  
       2013-05-20 09:42:13 +08:00
    看你的key是什么样的,还有你的具体需求。排序的话,
    可以用 heapq

    h = []
    heappush(h, ('key8', 'write code'))
    heappush(h, ('key1', 'release product'))
    heappush(h, ('key3', 'write spec'))
    heappush(h, ('key6', 'create tests'))

    heappop(h)
    # ('key1', 'release product')
    heappop(h)
    # ('key3', 'write spec')
    heappop(h)
    # ('key3', 'write spec')
    heappop(h)
    # ('key8', 'write code')
    DH
        9
    DH  
       2013-05-20 09:47:06 +08:00
    还可以用 bisect

    h = []
    bisect.insort_left(h, ('key1', 'test'))
    bisect.insort_left(h, ('key2', 'test'))
    bisect.insort_left(h, ('key0', 'test'))

    h
    # [('key0', 'test'), ('key1', 'test'), ('key2', 'test')]
    reusFork
        10
    reusFork  
       2013-05-20 12:00:53 +08:00 via Android
    用heap
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1025 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:36 · PVG 03:36 · LAX 12:36 · JFK 15:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.