I have a result like this:
{
"read":["English"],
"speak":["English", "French", "Portuguese", "German"],
"write":[],
"fluency":[]
}
my data mapper:
{
language:{
speak:[],
write:[],
read:[],
fluency:[]
}
}
I want to display the result in a readable format like below:
English - speak, read
French - speak
Italian - speak
German - speak
1st Attempt:
{% for key, value in profile.get('language', '') %}
{% for fluency, skills in value.items() %}
<li>{{skills}}, {{fluency}} - {{(', ').join(key)}}</li>
{% endfor %}
{% endfor %}
Error:
valueerror: too many values to unpack (expected 2)
I tried but didn't work, how can I achieve this?
CodePudding user response:
This should work for you.
Code:
from collections import defaultdict
json_data = {
"language":{
"read":["English"],
"speak":["English", "French", "Portuguese", "German"],
"write":[],
"fluency":[]
}
}
data = json_data.get('language', {})
res_dict = defaultdict(list)
for fluency, skills in data.items():
for skill in skills:
res_dict[skill].append(fluency)
for key, val in res_dict.items():
lanuage = key
fluency = ', '.join(val)
print(f'{lanuage} - {fluency}')
Output:
English - read, speak
French - speak
Portuguese - speak
German - speak
CodePudding user response:
First find a list of unique languages then retrieve the keys from the original dictionaries to make desired string output.
d = {
"read":["English"],
"speak":["English", "French", "Portuguese", "German"],
"write":[],
"fluency":[]
}
langs = []
for v in d.values():
for i in v:
if i not in langs:
langs = [i]
print(langs)
outputs = []
for l in langs:
output = [l]
for k, v in d.items():
if l in v:
output = [k]
outputs = [output]
result = '\n'.join([f'{s[0]} - ' ', '.join(s[1:]) for s in outputs])
print(result)
Output
English - read, speak
French - speak
Portuguese - speak
German - speak
CodePudding user response:
First I would suggest to transform your dataset:
data = {
"read":["English"],
"speak":["English", "French", "Portuguese", "German"],
"write":[],
"fluency":[]
}
def transform_data(data):
lang = []
[lang.extend(data[k]) for k in data]
new_dict = {}
for l in set(lang):
new_dict[l] = []
for k in data:
if l in data[k]:
new_dict[l].append(k)
return new_dict
new_data = transform_data(data)
new_data =
{'German': ['speak'],
'English': ['read', 'speak'],
'French': ['speak'],
'Portuguese': ['speak']}
Then you can create a function which can print the data in a format you desire.
for example:
for k in new_data:
print(f"{k} - {', '.join(new_data[k])}")
Output:
English - read, speak
French - speak
German - speak
Portuguese - speak