Lists inside dictionary and how to look for particular value

Peter Otten __peter__ at web.de
Sun Jan 26 14:44:21 EST 2014


mick verdu wrote:

> z={ 'PC2': ['02:02:02:02:02:02', '192.168.0.2', '200'],
>     'PC3': ['03:03:03:03:03:03', '192.168.0.3', '200'],
>     'PC1': ['01:01:01:01:01:01', '192.168.0.1', '200'] }
> 
> My solution:
> 
> z=raw_input("Enter Host, Mac, ip and time")
> t=z.split()
> t[0]=z[1:]
> for key in dic:
>     if t[2] in dic[key]:
>         del dic[t[0]]
>     else:
>         dic[t[0]] = t[1:]
> 
> 
> What I really want to achieve is:
> 
> 
> How to search for a particular value inside list. First, I want the user
> to input hostname and ip. e.g. PC1 and 192.168.0.1, then need to find out
> if 192.168.0.1 has already been assigned to some host in dictionary. In
> this case I would need to skip for search inside list of user input host.
> 
> Forexample, if user inputs PC1 and 192.168.0.1 i would like to skip
> searching in above PC1's values. So it should detect matching only with
> different hosts and skip its own name.
> 
> If i input PC4 and 192.168.0.1 then it should detect conflict with PC1. So
> PC4 would be deleted(As soon as user inputs new host it is saved in above
> database then if conflict with others deleted)

You are making the problem unnecessarily complex. For the example scenario 
start with a dict that maps host to ip:

host2ip = {
 "PC1": "192.168.0.1",
 "PC2": "192.168.0.2",
 "PC3": "192.168.0.3",
}

host, ip = raw_input("Enter host and ip: ").split()
if host not in host2ip:
    print "adding", host
    host2ip[host] = ip
else:
    old_ip = host2ip[host]
    if old_ip == ip:
        print "no changes necessary"
    else:
        print "updating ip for", host, "from", old_ip, "to", ip
        host2ip[host] = ip


Then proceed and come up with an unambiguous description of what to do with 
mac and time in plain english, and add or modify data structures as 
necessary.




More information about the Python-list mailing list