[Python] Combineren van meerdere dictionaries

Pagina: 1
Acties:

Vraag


Acties:
  • 0 Henk 'm!

  • BlaTieBla
  • Registratie: November 2000
  • Laatst online: 22-09 11:02

BlaTieBla

Vloeken En Raak Schieten

Topicstarter
Mijn vraag
Ik heb meerdere dictiomaries met data. Qua structuur / inhoud zijn deze te vergelijken met bijv. relationele database tabellen. Er worden dus referenties / id's gebruikt die verwijzen naar data in andere tabellen.
Bijvoorbeeld
code:
1
2
3
4
colors = [{'id': 1, 'name': 'red'}, {'id': 2, 'name': 'blue'}, {'id': 3, 'name': 'white'}]

articles = [{'id': 'a', 'color': 1, 'item': 'car'}, {'id': 'b', 'color': 3, 'item': 'bike'},
            {'id': 'c', 'color': 2, 'item': 'boat'}]

in bovenstaand voorbeeld verwijst de color in de articles dict naar een kleur in de colors dict.

Nu wil ik een nieuwe dict maken waarin de kleur referenties vervangen worden voor de naam van de kleur;
code:
1
2
result = [{'id': 'a', 'color': 'red', 'item': 'car'}, {'id': 'b', 'color': 'white', 'item': 'bike'},
          {'id': 'c', 'color': 'blue', 'item': 'boat'}]


Wie kan mij in de juiste richting duwen?

Relevante software en hardware die ik gebruik
Python 3.6+

Wat ik al gevonden of geprobeerd heb
Via een iteratief proces krijg ik dat wel voor elkaar, maar ik heb het donkerbruine vermoeden dat het veel efficiënter/korter kan. Op basis van bjiv. SQL kan je met joins aan de gang. Via Python zal dit ook kunnen, maar ik kom er niet op en kan op het internet ook weinig vinden. Heeft waarschijnlijk te maken met dat ik net niet de juiste term weet/herken om dit te doen.

leica - zeiss - fuji - apple | PSN = Sh4m1n0

Alle reacties


Acties:
  • 0 Henk 'm!

  • Compizfox
  • Registratie: Januari 2009
  • Laatst online: 01-10 18:52

Compizfox

Bait for wenchmarks

Als je geen puur (Standard Library) Python hoeft te zijn, zou ik eens kijken naar Pandas: https://pandas.pydata.org...ed-series-joining-merging

Gewoon een heel grote verzameling snoertjes


Acties:
  • 0 Henk 'm!

  • BlaTieBla
  • Registratie: November 2000
  • Laatst online: 22-09 11:02

BlaTieBla

Vloeken En Raak Schieten

Topicstarter
Daar had ik ook al naar gekeken, omdat het dan heel erg gaat lijken op de SQL manier (waar ik enigszins bekend mee ben). Maar als het enigszins kan dan zonder externe libraries.

Het beschreven voorbeeld is relatief eenvoudig en onderstaande code levert een aangepaste articles lijst met het gewenste resultaat. De toepassing waarvoor ik het wil gebruiken heeft echter 5-10 referenties per dict in de lijst en dan wordt het een lange constructie van loops en if-statements.

Python:
1
2
3
4
for article in articles:
    for color in colors:
        if article['color'] == color['id']:
            article['color'] = color['name']

leica - zeiss - fuji - apple | PSN = Sh4m1n0


Acties:
  • +1 Henk 'm!

  • ValHallASW
  • Registratie: Februari 2003
  • Niet online
Als je je lijst-met-kleuren eerst daadwerkelijk in een dictionary omzet, iaw
Python:
1
2
# colors = { color['id']: color['name'], ... }
colors = {1: 'red', 2: 'blue', 3: 'white'}


dan kan je vervolgens de kleur simpelweg opzoeken met
Python:
1
colors[article['color']]


Als je een fallback wilt hebben als de kleur niet bestaat kan je nog gebruik maken van dict.get:
Python:
1
colors.get(article['color'], 'default-color')

Acties:
  • 0 Henk 'm!

  • BlaTieBla
  • Registratie: November 2000
  • Laatst online: 22-09 11:02

BlaTieBla

Vloeken En Raak Schieten

Topicstarter
ValHallASW schreef op zondag 25 juli 2021 @ 14:03:
Als je je lijst-met-kleuren eerst daadwerkelijk in een dictionary omzet, iaw
Python:
1
2
# colors = { color['id']: color['name'], ... }
colors = {1: 'red', 2: 'blue', 3: 'white'}

[...]
Het voorbeeld is wat minder complex dan de werkelijkheid. De dictionaries zijn een stuk uitgebreider, dus die omzetting gaat helaas niet werken.
Maar je voorbeeld ga ik wel onthouden, want die manier kende ik nog niet (learning something every day :) )

leica - zeiss - fuji - apple | PSN = Sh4m1n0


Acties:
  • +1 Henk 'm!

  • ValHallASW
  • Registratie: Februari 2003
  • Niet online
Kan je dan een iets realistischer voorbeeld geven? ;-)

In principe zou dezelfde techniek voor elke soort lookup moeten werken -- het kan wel zijn dat je meerdere dicts nodig hebt (net afhankelijk van op welke kolom(men) je 'join't), en het kan zijn dat je een composite key nodig hebt, maar dat kan prima:

code:
1
colors = {('colorscheme1', 1): 'red', ....}


(maargoed, dan kom je wel op het punt waar pandas of sqlite de moeite waard gaat worden).

Acties:
  • 0 Henk 'm!

  • BlaTieBla
  • Registratie: November 2000
  • Laatst online: 22-09 11:02

BlaTieBla

Vloeken En Raak Schieten

Topicstarter
ValHallASW schreef op zondag 25 juli 2021 @ 18:31:
Kan je dan een iets realistischer voorbeeld geven? ;-)

In principe zou dezelfde techniek voor elke soort lookup moeten werken -- het kan wel zijn dat je meerdere dicts nodig hebt (net afhankelijk van op welke kolom(men) je 'join't), en het kan zijn dat je een composite key nodig hebt, maar dat kan prima:

code:
1
colors = {('colorscheme1', 1): 'red', ....}


(maargoed, dan kom je wel op het punt waar pandas of sqlite de moeite waard gaat worden).
Ik heb wel een voorbeeld (wel een beetje ingekort).
Een kleine toelichting op de data; Het gaat om JSON responses vanuit API calls. Ik heb in de onderstaande output wel geanonimiseerd. Plus de inkorting kan er voor zorgen dat de data incompleet is waardoor je het niet direct kan gebruiken.

Anyhow, het gaat om een hiërarchisch model waarbij je het hebt over een IP SPACE (TOP), onderliggende netwerken (LEVEL 1) en dhcp ranges (LEVEL 2). Deze worden onderling verbonden d.m.v. id verwijzingen. Dus range valt in een netwerk en een netwerk binnen een IP space. Maar gezien de ref_id's blijft het daar niet bij (tip of the iceberg).

Voor een aantal zaken wil ik (om het leesbaar te maken en verder te kunnen verwerken in bijv. rapportage) de referentie id's vervangen voor de (bovenliggende object naam).

JSON:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
TOP:
{
    "results": [
        {
            "dhcp_config": {
                "allow_unknown": true,
                "filters": [],
                "ignore_list": [],
                "lease_time": 3600
            },
            "dhcp_options": [
                {
                    "group": null,
                    "option_code": "dhcp/option_code/65fc9722-80a2-422b-ad88-8bcba94e82f0",
                    "option_value": "10.15.240.132,10.15.240.133,10.19.240.132,10.19.240.133",
                    "type": "option"
                },
                {
                    "group": null,
                    "option_code": "dhcp/option_code/8004690b-bb4d-47d3-bdbb-ee485e36a0c4",
                    "option_value": "int.local.com",
                    "type": "option"
                }
            ],
            "id": "ipam/ip_space/5c11e088-e303-11eb-b488-aaa4a0345ab6",
            "name": "Company Name"
        }
    ]
}



LEVEL 1:
{
    "results": [
        {
            "address": "192.168.16.0",
            "asm_config": {
                "asm_threshold": 0,
                "enable": true,
                "enable_notification": true,
                "forecast_period": 14,
                "growth_factor": 0,
                "growth_type": "percent",
                "history": 30,
                "min_total": 10,
                "min_unused": 0,
                "reenable_date": "1970-01-01T00:00:00Z"
            },
            "asm_scope_flag": 0,
            "cidr": 24,
            "created_at": "2021-07-16T07:33:08.021148Z",
            "ddns_domain": "",
            "dhcp_config": {
                "allow_unknown": true,
                "filters": [],
                "ignore_list": [],
                "lease_time": 3600
            },
            "dhcp_host": "dhcp/ha_group/031965c6-e62f-11eb-9704-a6e6b0c5732d",
            "dhcp_options": [
                {
                    "group": null,
                    "option_code": "dhcp/option_code/65fc9722-80a2-422b-ad88-8bcba94e82f0",
                    "option_value": "8.8.8.8,8.8.4.4",
                    "type": "option"
                },
                {
                    "group": null,
                    "option_code": "dhcp/option_code/185ffc35-eb8a-4313-8d3c-ae174e3bc4c4",
                    "option_value": "192.168.16.254",
                    "type": "option"
                },
                {
                    "group": null,
                    "option_code": "dhcp/option_code/8004690b-bb4d-47d3-bdbb-ee485e36a0c4",
                    "option_value": "int.domain.com",
                    "type": "option"
                }
            ],
            "dhcp_utilization": {
                "dhcp_free": "248",
                "dhcp_total": "248",
                "dhcp_used": "0",
                "dhcp_utilization": 0
            },
            "id": "ipam/subnet/10bf67ff-e608-11eb-bf54-72ce1c8ff6f0",
            "inheritance_assigned_hosts": [],
            "inheritance_parent": null,
            "inheritance_sources": null,
            "parent": null,
            "protocol": "ip4",
            "space": "ipam/ip_space/5c11e088-e303-11eb-b488-aaa4a0345ab6",
            "tags": null,
            "threshold": {
                "enabled": false,
                "high": 0,
                "low": 0
            },
            "updated_at": "2021-07-25T14:28:02.552631Z",
            "utilization": {
                "abandon_utilization": 0,
                "abandoned": "0",
                "dynamic": "0",
                "free": "252",
                "static": "4",
                "total": "256",
                "used": "4",
                "utilization": 2
            }
        },
        {
            "address": "192.23.70.0",
            "asm_config": {
                "asm_threshold": 0,
                "enable": true,
                "enable_notification": true,
                "forecast_period": 14,
                "growth_factor": 0,
                "growth_type": "percent",
                "history": 30,
                "min_total": 10,
                "min_unused": 0,
                "reenable_date": "1970-01-01T00:00:00Z"
            },
            "asm_scope_flag": 0,
            "cidr": 23,
            "created_at": "2021-07-12T12:38:35.566757Z",
            "ddns_domain": "",
            "dhcp_config": {
                "allow_unknown": true,
                "filters": [],
                "ignore_list": [],
                "lease_time": 3600
            },
            "dhcp_host": "dhcp/ha_group/031965c6-e62f-11eb-9704-a6e6b0c5732d",
            "dhcp_options": [],
            "dhcp_utilization": {
                "dhcp_free": "0",
                "dhcp_total": "0",
                "dhcp_used": "0",
                "dhcp_utilization": 0
            },
            "id": "ipam/subnet/132a6bdb-e30e-11eb-a2dc-9accd3c7acee",
            "inheritance_assigned_hosts": [],
            "inheritance_parent": null,
            "inheritance_sources": null,
            "parent": null,
            "protocol": "ip4",
            "space": "ipam/ip_space/5c11e088-e303-11eb-b488-aaa4a0345ab6",
            "tags": null,
            "threshold": {
                "enabled": false,
                "high": 0,
                "low": 0
            },
            "updated_at": "2021-07-25T14:28:02.659432Z",
            "utilization": {
                "abandon_utilization": 0,
                "abandoned": "0",
                "dynamic": "0",
                "free": "508",
                "static": "4",
                "total": "512",
                "used": "4",
                "utilization": 1
            }
        }
    ]
}



LEVEL 2:
{
    "results": [
        {
            "created_at": "2021-07-21T10:12:17.079625Z",
            "dhcp_host": "dhcp/ha_group/201e316a-e9fc-11eb-b205-fe0211591dc3",
            "dhcp_options": [],
            "end": "192.168.255.12",
            "exclusion_ranges": [],
            "id": "ipam/range/207fb191-ea0c-11eb-b205-fe0211591dc3",
            "inheritance_assigned_hosts": [],
            "inheritance_parent": "ipam/subnet/efe7aa16-ea0b-11eb-bf54-72ce1c8ff6f0",
            "inheritance_sources": null,
            "name": "",
            "parent": "ipam/subnet/efe7aa16-ea0b-11eb-bf54-72ce1c8ff6f0",
            "protocol": "ip4",
            "space": "ipam/ip_space/5c11e088-e303-11eb-b488-aaa4a0345ab6",
            "start": "192.168.255.11",
            "tags": null,
            "threshold": {
                "enabled": false,
                "high": 0,
                "low": 0
            },
            "updated_at": "2021-07-21T10:12:18.135485Z",
            "utilization": {
                "abandon_utilization": 0,
                "abandoned": "0",
                "dynamic": "0",
                "free": "2",
                "static": "0",
                "total": "2",
                "used": "0",
                "utilization": 0
            }
        },
        {
            "created_at": "2021-07-16T07:40:54.845967Z",
            "dhcp_host": null,
            "dhcp_options": [],
            "end": "192.168.130.248",
            "exclusion_ranges": [],
            "id": "ipam/range/27002a82-e609-11eb-b205-fe0211591dc3",
            "inheritance_assigned_hosts": [],
            "inheritance_parent": "ipam/subnet/aef619a2-e30d-11eb-b488-aaa4a0345ab6",
            "inheritance_sources": null,
            "name": "",
            "parent": "ipam/subnet/aef619a2-e30d-11eb-b488-aaa4a0345ab6",
            "protocol": "ip4",
            "space": "ipam/ip_space/5c11e088-e303-11eb-b488-aaa4a0345ab6",
            "start": "192.168.130.1",
            "tags": null,
            "threshold": {
                "enabled": false,
                "high": 0,
                "low": 0
            },
            "updated_at": "2021-07-16T07:41:11.122739Z",
            "utilization": {
                "abandon_utilization": 0,
                "abandoned": "0",
                "dynamic": "0",
                "free": "248",
                "static": "0",
                "total": "248",
                "used": "0",
                "utilization": 0
            }
        },
        {
            "created_at": "2021-07-16T07:37:27.200771Z",
            "dhcp_host": null,
            "dhcp_options": [],
            "end": "192.168.16.248",
            "exclusion_ranges": [],
            "id": "ipam/range/ab33ae85-e608-11eb-9704-a6e6b0c5732d",
            "inheritance_assigned_hosts": [],
            "inheritance_parent": "ipam/subnet/10bf67ff-e608-11eb-bf54-72ce1c8ff6f0",
            "inheritance_sources": null,
            "name": "",
            "parent": "ipam/subnet/10bf67ff-e608-11eb-bf54-72ce1c8ff6f0",
            "protocol": "ip4",
            "space": "ipam/ip_space/5c11e088-e303-11eb-b488-aaa4a0345ab6",
            "start": "192.168.16.1",
            "tags": null,
            "threshold": {
                "enabled": false,
                "high": 0,
                "low": 0
            },
            "updated_at": "2021-07-16T07:38:13.836196Z",
            "utilization": {
                "abandon_utilization": 0,
                "abandoned": "0",
                "dynamic": "0",
                "free": "248",
                "static": "0",
                "total": "248",
                "used": "0",
                "utilization": 0
            }
        }
    ]
}

leica - zeiss - fuji - apple | PSN = Sh4m1n0


Acties:
  • 0 Henk 'm!

  • ValHallASW
  • Registratie: Februari 2003
  • Niet online
Python:
1
2
3
4
5
6
7
8
TOP_lookup = {x['id']: x['name'] for x in TOP['results']}

def inject_L1(l1_entry):
  result = copy.deepcopy(l1_entry)
  result['space_human'] = TOP_lookup[l1_entry['space']]  
  return result

L1_cleaned = [inject(x) for x in L1['results']]


etc?

Sterker nog, omdat je keys allemaal netjes geprefixt zijn kan je zelfs een enkele lookup-dict maken (ipv een per type), waar álle id -> human_readable_name mappings instaan.

Acties:
  • 0 Henk 'm!

  • BlaTieBla
  • Registratie: November 2000
  • Laatst online: 22-09 11:02

BlaTieBla

Vloeken En Raak Schieten

Topicstarter
ValHallASW schreef op maandag 26 juli 2021 @ 09:13:
Python:
1
2
3
4
5
6
7
8
TOP_lookup = {x['id']: x['name'] for x in TOP['results']}

def inject_L1(l1_entry):
  result = copy.deepcopy(l1_entry)
  result['space_human'] = TOP_lookup[l1_entry['space']]  
  return result

L1_cleaned = [inject(x) for x in L1['results']]


etc?

Sterker nog, omdat je keys allemaal netjes geprefixt zijn kan je zelfs een enkele lookup-dict maken (ipv een per type), waar álle id -> human_readable_name mappings instaan.
Thanks. Ik ga hier eens mee aan de slag.

leica - zeiss - fuji - apple | PSN = Sh4m1n0


Acties:
  • 0 Henk 'm!

  • Ed Vertijsment
  • Registratie: Juli 2014
  • Laatst online: 21:53
Mijn (python3) oplossing middels een list comprehension, dictionairy unpacking en een filter.

Input:
Python:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
colors = [{'id': 1, 'name': 'red'}, {'id': 2, 'name': 'blue'}, {'id': 3, 'name': 'white'}]

articles = [{'id': 'a', 'color': 1, 'item': 'car'}, {'id': 'b', 'color': 3, 'item': 'bike'},
            {'id': 'c', 'color': 2, 'item': 'boat'}]


result = [  # Maak list.
  {  # Elk item is dict.
    **article,  # Alle key/values van huidige item "article" van list "articles".
    'color': # Overschrijf key "color"
        next(  # Volgende item van iterable van filter.
            filter(
                lambda c: c['id'] == article['color'],  # Filtert item waar waarde van id gelijk is aan article['id'].
                colors  # Uit colors list.
            )
        )
        ['name']  # Naam van kleur als value voor key "color".
  }
  
  for article in articles # List comprehension.
]


print(result)  # Print resultaat.


Output:
[{'id': 'a', 'color': 'red', 'item': 'car'}, {'id': 'b', 'color': 'white', 'item': 'bike'}, {'id': 'c', 'color': 'blue', 'item': 'boat'}]

Acties:
  • 0 Henk 'm!

  • BlaTieBla
  • Registratie: November 2000
  • Laatst online: 22-09 11:02

BlaTieBla

Vloeken En Raak Schieten

Topicstarter
Door wat escalaties op het werk nog niet toegekomen om de aangedragen oplossingen te testen :|

leica - zeiss - fuji - apple | PSN = Sh4m1n0

Pagina: 1