coolair
V2EX  ›  问与答

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

  •  
  •   coolair · Aug 3, 2019 · 2650 views
    This topic created in 2657 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   ·   2398 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 12:14 · PVG 20:14 · LAX 04:14 · JFK 07:14
    ♥ Do have faith in what you're doing.