Reputation: 315
Suppose I have a dictionary (dict) with keys and values as below:
print(dict)
{'AAA': {'', '111', '222'}, 'BBB': {'222', '999', '555'}}
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'
but what I am getting is below under dict.values()
:
dict.keys()
dict_keys(['AAA', 'BBB'])
dict.values()
dict_values([{'', '111', '222'}, {'222', '999', '555'}])
How can I achieve the required result?
Upvotes: 1
Views: 25270
Reputation: 12669
You can try list comprehension in one line :
data={'AAA': {'', '111', '222'}, 'BBB': {'222', '999', '555'}}
print(set([k for i,j in data.items() for k in j if k]))
output:
{'222', '999', '111', '555'}
Upvotes: 0
Reputation: 10729
This is another way to do without import any module.
dict = {'AAA': {'', '111', '222'}, 'BBB': {'222', '999', '555'}}
result = []
print([[result.append(item) or item for item in one_set if item] for one_set in dict.values()])
print(','.join(result)) #all non '' elements
print(','.join(set(result))) #all non '' and non duplicated elements
Output:
[['222', '111'], ['222', '999', '555']]
222,111,222,999,555
222,999,555,111
[Finished in 0.181s]
Upvotes: 0
Reputation: 194
Just use extend
method:
values = []
for key in some_dict:
values.extend(list(some_dict[key]))
If you need to delete the empty strings, use:
values = list(filter(None, values))
See this SE entry
Then you can convert it to a tuple if you wish :)
Upvotes: 0
Reputation: 76907
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'}
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)
Upvotes: 5
Reputation:
Do you want something like
d = dict()
d[0] = '0'
str(d)
?
String manipulations are fairly straightforward after that
Upvotes: 0
Reputation: 9019
I believe this is what you are after if you want them output as a single string:
mydict = {'AAA': {'', '111', '222'}, 'BBB': {'222', '999', '555'}}
out = []
for keys, values in mydict.items():
[out.append(i) for i in values if i!='']
out = ','.join(set(out))
print(out)
print(type(out))
Outputs:
555,222,111,999
<class 'str'>
Upvotes: 0