python how to slice a dictionary

时间:2018-03-25 19:53:56

标签: python dictionary

what I have:

[{'model': 're_catalogue.component', 'pk': 1, 'fields': {'name': 'Solar modules', 'name_el': 'Φωτοβολταικά πλαίσια', 'name_de': 'Solarmodul'}}, {'model': 're_catalogue.component', 'pk': 2, 'fields': {'name': 'DC cables', 'name_el': 'DC καλώδια', 'name_de': 'DC-Kabel'}}, {'model': 're_catalogue.component', 'pk': 3, 'fields': {'name': 'DC combiner boxes', 'name_el': 'DC πίνακες', 'name_de': 'DC-Anschlussgehäuse'}}]

for i in range (0,20):
    print(d[i])

The output

{'model': 're_catalogue.component', 'pk': 1, 'fields': {'name': 'Solar modules', 'name_el': 'Φωτοβολταικά πλαίσια', 'name_de': 'Solarmodul'}}
{'model': 're_catalogue.component', 'pk': 2, 'fields': {'name': 'DC cables', 'name_el': 'DC καλώδια', 'name_de': 'DC-Kabel'}}
{'model': 're_catalogue.component', 'pk': 3, 'fields': {'name': 'DC combiner boxes', 'name_el': 'DC πίνακες', 'name_de': 'DC-Anschlussgehäuse'}}
{'model': 're_catalogue.component', 'pk': 4, 'fields': {'name': 'Inverters', 'name_el': 'Μετατροπείς', 'name_de': 'Wechselrichter'}}
{'model': 're_catalogue.component', 'pk': 5, 'fields': {'name': 'AC cables', 'name_el': 'ΑC καλώδια', 'name_de': 'AC-Kabel'}}
{'model': 're_catalogue.component', 'pk': 6, 'fields': {'name': 'AC combiner boxes', 'name_el': 'AC πίνακες', 'name_de': 'AC-Anschlussgehäuse'}}

what I need is a json file that includes only the 'name' and 'name_el' like the following:

{
"Solar modules": "Φωτοβολταικά πλαίσια",
"DC cables": "DC καλώδια",
}

Thank you for any help. At the same time I am trying to solve it as well.

3 个答案:

答案 0 :(得分:3)

By using a dict comprehension you'll get a dict with the desired output (assuming your list of dicts is called lst ):

{i['fields']['name']:i['fields']['name_el'] for i in lst}

答案 1 :(得分:2)

If i get your question right, this is what you want:

lst = [
    {'model': 're_catalogue.component', 'pk': 1, 'fields': {'name':'Solar modules', 'name_el': 'Φωτοβολταικά πλαίσια', 'name_de': 'Solarmodul'}},
    {'model': 're_catalogue.component', 'pk': 2, 'fields': {'name': 'DC cables', 'name_el': 'DC καλώδια', 'name_de': 'DC-Kabel'}}
]

result = dict()
for i in lst:
    result[i['fields']['name']] = i['fields']['name_el']
print(result)
# {
#    "Solar modules": "Φωτοβολταικά πλαίσια",
#    "DC cables": "DC καλώδια"
# }

答案 2 :(得分:1)

new_dict = {}
for e in d:
    new_dict[e['fields']['name']] = e['fields']['name_el']