将字典值转换为Python中的列表

问题描述:

假设我有一个字典(dict),其键和值如下:

Suppose I have a dictionary (dict) with keys and values as below:


print(dict)

print(dict)



{'AAA': {'', '111', '222'}, 'BBB': {'222', '999', '555'}}

我想从字典中提取值以单个字符串的形式,即 type(values)= str ,例如:

I want to extract the values from the dictionary in the form of a single string, i.e. type(values) = str, such as:

values = '111', '222', '999', 555'

但是我得到的却是在 dict.values()下:

but what I am getting is below under dict.values():


dict.keys()

dict.keys()



dict_keys(['AAA', 'BBB'])




dict.values()

dict.values()



dict_values([{'', '111', '222'}, {'222', '999', '555'}])

如何获得所需的结果?

您可以使用 itertools.chain 来做到这一点:

You can use itertools.chain to do this:

In [92]: from itertools import chain

In [93]: dct = {'AAA': {'', '111', '222'}, 'BBB': {'222', '999', '555'}}

In [94]: {x for x in chain(*dct.values()) if x}
Out[94]: {'111', '222', '555', '999'}

如果要将此输出转换为单个字符串,只需对其使用 str()调用,或使用, .join(x代表链中x(* dct.values()),如果x)

If you want to convert this output to a single string, just use an str() call on it, or use ", ".join(x for x in chain(*dct.values()) if x)