How do I filter out non-string keys in a dictionary in Python?

前端 未结 5 1383
星月不相逢
星月不相逢 2021-01-24 07:13

I\'m new to Python and trying to figure out how to filter out all the non-string keys in a dictionary. I appreciate any help you can provide.

相关标签:
5条回答
  • 2021-01-24 07:46

    For sake of variety of answers, here is another method:

    >>> d = {1: 'ONE', 2: 'TWO', 3: 'THREE', 'T': 'THREE'}
    >>> b = {k:d[k] for k in filter(lambda s: type(s) is int, d.iterkeys())}
    >>> b
    {1: 'ONE', 2: 'TWO', 3: 'THREE'}
    
    0 讨论(0)
  • 2021-01-24 07:47
    new = {k, v for k, v in old.items() if isinstance(k, str)} # repair items if key is string
    
    0 讨论(0)
  • 2021-01-24 07:51
    is_str = 'foo'
    not_str = 34
    dd = {is_str:12, not_str:13, 'baz':14, 1:15}
    for k in dd: print k, isinstance(k, str)
    

    note that this is set up with not just literal string keys but variables that may or may not refer to strings. Whatever filter you want (keep, delete, operate on) could go inside the for loop.

    Also, do you know about duck-typing? You might not need to actually get rid of string-keyed items; sometimes Python will do the sensible stringish thing with a non-string.

    0 讨论(0)
  • 2021-01-24 07:54

    You can use dict.keys() to get a list of the keys, use type() to check the type of the key, and then utilize an if-statement to check the type against type(""), and potentially delete the key and its pair. Following code contains spoilers.

    for key in dict.keys():            #Loop through
        if type(key) != type(""):      #Check the type
            del dict[key]              #Potentially delete key and value
    
    0 讨论(0)
  • 2021-01-24 08:01
     { key: dict[key] for key in dict.keys() if isinstance(key, int) }
    
    0 讨论(0)
提交回复
热议问题