I have a dictionary where
the value for each key is a list.
> {"Market":['market', 'shop', 'shopping']}
I want the values to be separated by pipe i.e
> {'Market':'market|shop|shopping'}
I tried out few lines of code
for keys, values in pydict.items():
values = "|".join(values)
mynew[keys] =
print(keys, values)
I tried out but not getting the final answer.
CodePudding user response:
Use a dictionary comprehension:
>>> x = {"Market":['market', 'shop', 'shopping'], "SomethingElse": ["foo", "bar"]}
>>> y = {k: "|".join(v) for (k, v) in x.items()}
{'Market': 'market|shop|shopping', 'SomethingElse': 'foo|bar'}`
CodePudding user response:
You can iterate over dict
and use '|'.join()
on values like below:
>>> dct = {"Market":['market', 'shop', 'shopping'], "Market2":['market', 'shop', 'shopping']}
>>> {k: '|'.join(item for item in v) for k,v in dct.items()}
{'Market': 'market|shop|shopping', 'Market2': 'market|shop|shopping'}
CodePudding user response:
You can use the dict comprehension like @AKX pointed out or you can also modify the dict values in place.
>>> x = {"Market":['market', 'shop', 'shopping'], "SomethingElse": ["foo", "bar"]}
>>> for k,v in x.items():
... x[k] = "|".join(v)
...
>>> x
{'Market': 'market|shop|shopping', 'SomethingElse': 'foo|bar'}
>>>