I have a dictionary, and I am using this code to print its first 3 key—value pairs.
[print(v) for i, v in enumerate(dict_data.items()) if i < 2]
Output:
(1, ['qd inc', 'san diego', '11578 sorrento valley road'])
(2, ['argon jg hannoosh', 'phil mag', 'initiation crazes polystyrene'])
I want to split the values of each key into the space, so my desired output is:
Desired Output:
(1, ['qd', 'inc', 'san', 'diego', '11578', 'sorrento', 'valley', 'road'])
(2, ['argon', 'jg', 'hannoosh', 'phil', 'mag', 'initiation', 'crazes', 'polystyrene'])
I tried running this code but I get an error! (AttributeError: 'list' object has no attribute 'split')
dict_data = {key: [int(val) for val in value.split()] for key, value in dict_data.items()}
CodePudding user response:
Try this:
new_dict = {}
for key, value in dict_data.items():
for phrase in value:
new_dict.setdefault(key, []).extend(phrase.split())
CodePudding user response:
IIUC, If Your input dict
be like below, You can use itertools.chain.from_iterable.
from itertools import chain
dct = {
1 : ['qd inc', 'san diego', '11578 sorrento valley road'] ,
2 : ['argon jg hannoosh', 'phil mag', 'initiation crazes polystyrene']
}
res = {k: list(chain.from_iterable([st.split() for st in v])) for k,v in dct.items()}
print(res)
{
1: ['qd', 'inc', 'san', 'diego', '11578', 'sorrento', 'valley', 'road'],
2: ['argon', 'jg', 'hannoosh', 'phil', 'mag', 'initiation', 'crazes', 'polystyrene']
}