python - Why what's wrong with this dict conversion of a lambda expression result object? -
was feeling smug thinking had best lambda expression in universe cooked return relevant network information ever needed using python , netifaces
>>> list(map(lambda interface: (interface, dict(filter(lambda ifaddress: ifaddress in (netifaces.af_inet, netifaces.af_link), netifaces.ifaddresses(interface) ))) , netifaces.interfaces()))
but got this
traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 1, in <lambda> typeerror: cannot convert dictionary update sequence element #0 sequence
scaling bit
>>>dict(filter(lambda ifaddress: ifaddress in (netifaces.af_inet, netifaces.af_link), netifaces.ifaddresses("eth0")))
is problem is:
traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: cannot convert dictionary update sequence element #0 sequence
but can convert filter object list
>>> list(filter(lambda ifaddress: ifaddress in (netifaces.af_inet, netifaces.af_link), netifaces.ifaddresses("eth0"))) [17, 2]
but, that's not want. want is:
>>> netifaces.ifaddresses("tun2") {2: [{'addr': '64.73.0.0', 'netmask': '255.255.255.255', 'peer': '192.168.15.4'}]} >>> type (netifaces.ifaddresses("eth0")) <class 'dict'>
so what's mucking cast back dictionary?
when given dictionary input, filter
iterate , return keys dictionary.
>>> filter(lambda x: x > 1, {1:2, 3:4, 5:6}) [3, 5]
thus feeding sequence of filtered keys new dict, not key-value-pairs. fix this: note call items()
, how inner lambda
getting tuple input.
list(map(lambda interface: (interface, dict(filter(lambda tuple: tuple[0] in (netifaces.af_inet, netifaces.af_link), netifaces.ifaddresses(interface).items()))), netifaces.interfaces()))
now that's not pretty... suggest changing code nested list- , dictionary-comprehension:
[(interface, {ifaddress: value (ifaddress, value) in netifaces.ifaddresses(interface).items() if ifaddress in (netifaces.af_inet, netifaces.af_link)}) interface in netifaces.interfaces()]
Comments
Post a Comment