简体   繁体   中英

In Python, loop through a dict and set all values of list or dict to string

I have a dictionary "metadata" that contains key-value pairs of strings, lists, dicts, and integers. How can I loop through this dictionary and convert all values that are not of type string or integer to string?

Is there any way to simultaneously remove keys for which the value is empty? How could I do this without adding an additional loop?

Use isinstance to check the type of a value. In Python 3, you can simply write:

{k:v if isinstance(v, (str, int)) else str(v) for k,v in dct.items() if k != ''}

In older Python versions, you must be aware that there are no dictionary comprehensions (<2.7), and that there are multiple types that could be built-in ints and strings(<3). If you mean character strings when you talk about strings, the 2.5-2.7 equivalent would be

dict((k, v if isinstance(v, (unicode, int, long)) else unicode(v))
     for k,v in dct.iteritems())

This works:

d={'l':[1,2,3],'s':'abc','i':5,'f':1.23,'di':{1:'one',2:'two'},'emty':''}
{k:v if type(v) in (str,int, long,unicode) else repr(v) for k,v in d.items() if v!=''} 

Prints:

{'i': 5, 's': 'abc', 'di': "{1: 'one', 2: 'two'}", 'l': '[1, 2, 3]', 'f': '1.23'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM