Python Forum

Full Version: [SOLVED] Concat data from dictionary?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I don't know how to read all the data from a dictionary into a string:

"""
ipconfig:

[{'addr': '192.168.188.213', 'netmask': '255.255.255.0', 'broadcast': '192.168.188.255'}]
[{'addr': '192.168.0.12', 'netmask': '255.255.255.0', 'broadcast': '192.168.0.255'}]
[{'addr': '127.0.0.1', 'netmask': '255.0.0.0', 'broadcast': '127.255.255.255'}]
"""

from tkinter import Tk
from tkinter import messagebox
import netifaces

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing

output = ""
for interface in netifaces.interfaces():
	addrs = netifaces.ifaddresses(interface)
	if netifaces.AF_INET in addrs.keys():
		#print(addrs[netifaces.AF_INET])
		output += addrs(???)

messagebox.showinfo("Done", output)
Anybody knows?

Thank you.
What do you want the string to look like? str(addrs[netifaces.AF_INET]) will give you a string, but I assume it is not the string you want since you are asking the question.
I'd like to get something like this:

addr=192.168.0.12
netmask=255.255.255.0
broadcast=192.168.0.255
etc.
It looks like "join" is the way to go, but still NOK.

#ValueError: too many values to unpack (expected 2)		
for key,value in addrs[netifaces.AF_INET]:
	print(key,value)
from tkinter import Tk
from tkinter import messagebox
from itertools import chain
from ipaddress import ip_address

from netifaces import interfaces, ifaddresses, AF_INET, AF_INET6


Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing

results = []
for interface in interfaces():
    ipv4 = ifaddresses(interface).get(AF_INET, [])
    ipv6 = ifaddresses(interface).get(AF_INET6, [])
    for item in chain(ipv4, ipv6):
        addr = item["addr"]

        # filtering out loopback addresses
        if ip_address(addr).is_loopback:
            continue

        results.append(addr)


output = "\n".join(results)
messagebox.showinfo("Done", output)
Thanks a lot!