'Python one 'for' loop, multiple dictionary appends
com = self.get_scan_companies()
for name in com:
k.append({'org_id' : None, 'keyword' : name['names']})
for domain in com:
k.append({'org_id' : None, 'keyword' : domain['domains']})
for ip in com:
k.append({'org_id' : None, 'keyword' : ip['Ips']})
com generates a dictionary of {id,'names','domains','Ips'}
Note: com has 4 items but I need the last 3 only.
I want to enhance the code to one for loop with 3 lines of appends as above:
for name,domain,ip in com:
k.append({'org_id' : None, 'keyword' : name['names']})
k.append({'org_id' : None, 'keyword' : domain['domains']})
k.append({'org_id' : None, 'keyword' : ip['Ips']})
Expected result is a list:
k=[{'org_id' : None, 'keyword' : name['names']}, {'org_id' : None, 'keyword' : domain['domains']},{'org_id' : None, 'keyword' : ip['Ips']}]
I understand the above does not generate the result! Thanks for your help in advance!
Solution 1:[1]
The three for loops are all iterating over the same data. Calling the iterators name, domain, or ip makes no difference. This would be equivalent to the following single for loop using iter_ as a generic iterator:
com = self.get_scan_companies()
for iter_ in com:
k.append({'org_id' : None, 'keyword' : iter_['names']})
k.append({'org_id' : None, 'keyword' : iter_['domains']})
k.append({'org_id' : None, 'keyword' : iter_['Ips']})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DarrylG |
