coolair
V2EX  ›  问与答

Python 字典如何选择几个给定的 key,生成新的字典?

  •  
  •   coolair · Aug 3, 2019 · 2647 views
    This topic created in 2654 days ago, the information mentioned may be changed or developed.
    比如:
    data= {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    select(data, ['a', 'b']) == {'a': 1, 'b': 2}
    4 replies  •  2019-08-04 00:47:06 +08:00
    ZeldaPeach
    ZeldaPeach
    Aug 3, 2019
    1
    {k: data[k] for k in ('a','b')}
    Trim21
    Trim21
    Aug 3, 2019 via Android
    2
    用字典生成式
    Sylv
    Sylv
    Aug 3, 2019
    3
    new_keys = ['a', 'b']
    new_data = {key: data[key] for key in new_keys}
    shanguo
    shanguo
    Aug 4, 2019
    4
    >>> def select(src_dict, keys):
    ... return {k: src_dict[k] for k in keys if src_dict.get(k)}
    ...
    >>> d = dict(name='jok', age=20)
    >>> select(d, ['name'])
    {'name': 'jok'}
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4574 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 02:44 · PVG 10:44 · LAX 18:44 · JFK 21:44
    ♥ Do have faith in what you're doing.