简体   繁体   中英

Loop through queryset and a dictionary with similar keys in order

I have a django queryset containing information about network things. Primary key is IP. Then, I have a dictionary with IPs as keys containing some data.

I would like to display all IPs from either of the two sources in order, together with some info.

If an IP exists in the queryset, I don't care about the dictionary value.

For example, given:

<Queryset[{'ip':'10.2.2.2', 'type':'laptop', ...},
          {'ip':'10.4.4.4', 'type':'camera', ...},
          {'ip':'10.5.5.5', 'type':'iot',    ...},
          {'ip':'10.8.8.8', 'type':'switch', ...}]>

and:

{'10.1.1.1': 'foo', '10.4.4.4':'xxx', '10.6.6.6': 'bar', '10.9.9.9': 'baz'}

I want the following output:

10.1.1.1  foo
10.2.2.2  type: laptop ...
10.4.4.4  type: camera ...
10.5.5.5  type: iot ...
10.6.6.6  bar
10.8.8.8  type: switch ...
10.9.9.9  baz

I could do nested loops, but is there a neat pythonic way?

You really don't want to nest the loops. Since you don't care about the dict entry if it's in the query set, you can update the dict with the items from the query set, and those will be overwritten. Then you can sort the dict items all at once.

d.update(qs.values_list('ip', 'type'))

for k, v in sorted(d.items()):
    print(k, v)

Where d is the dict and qs is the query set.

If you still need the type: part printed off for items originally in the query set only, you can do the update a little differently.

d.update((k, 'type: '+v) for k, v in qs.values_list('ip', 'type'))

This prepends the string type: to every value from the query set before putting it in the dict.

It's not just type . For each IP I want either the whole object, or the string from the dictionary

Something like this, then?

d.update((o.ip, o) for o in qs)

You can set the value side of the pair to be whatever you want in the generator expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM