简体   繁体   English

在Python中,遍历一个dict并将list或dict的所有值设置为string

[英]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. 使用isinstance检查值的类型。 In Python 3, you can simply write: 在Python 3中,您可以简单地编写:

{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). 在较旧的Python版本中,您必须意识到没有字典理解(<2.7),并且内置int和字符串有多种类型(<3)。 If you mean character strings when you talk about strings, the 2.5-2.7 equivalent would be 如果你的意思是字符串当你谈论的字符串,则相当于2.5-2.7会

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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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