I have a dictionary like {"a":["b", "c", "d"], "b":["h", "i", "j"], "c":["k", "l", "m"]. I need to write a function that returns True if a requested key has requested value. Also, if "a" has "b" and "b" has "h", "i", and "j", then "a" has "b", "c", "d", "h", "i", "j". I wrote the following code and don't know what to do next:

def has_data(data, letter1, letter2):
    if letter2 in data[letter1]:
        return True
    else:
        return False

Can you help out?

You are trying to test a single value against a list that is nested inside of a dictionary which won't work. You will need to test for the existence of the key in the dictionary first, then perform any tests on the list that comes after it.

def has_data(data, letter1, letter2):
    if letter1 in data:
        if letter2 in data.get(letter1):
            return True
        else:
            return False
    else:
        return False

I have tested it and it does what you are wanting. I have also added a bit of code to it for testing purposes.

import random

items = {}
items["a"] = ["b", "c", "d"]
items["b"] = ["h", "i", "j"]
items["c"] = ["k", "l", "m"]

def has_data(data, letter1, letter2):
    if letter1 in data:
        if letter2 in data.get(letter1):
            return True
        else:
            return False
    else:
        return False

z = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
     'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

count = 1

while 1:
    rSamples = random.sample(z, 2)
    if has_data(items, rSamples[0], rSamples[1]):
        print "A match has occurred after", count, "iterations!"
        print rSamples
        break
    else:
        count += 1

Hope this helps!

here's my version of it :)

items = { "a":[ "b", "c", "d" ], "b":[ "h", "i", "j" ], "c":[ "k", "l", "m" ] }

def has_data( d, key, value ):
    availableValues = []

    if key not in d:
        print "Key not in found."
        return False
    if value in d[ key ]:
        return True
    else:
        for each in d[ key ]:
            if d.has_key( each ):
                availableValues += d[ each ]
        if value in availableValues:
            return True
    return False

#tests...
>>> print has_data( items, "a", "b" )
True
>>> print has_data( items, "a", "c" )
True
>>> print has_data( items, "a", "k" )
True
>>> print has_data( items, "a", "m" )
True
>>> print has_data( items, "b", "m" )
False
>>> print has_data( items, "a", "i" )
True
>>> print has_data( items, "d", "b" )
Key not in found.
False
>>>

hope it helps. Note that it only checks if the key has the value, it doesn't check the other way around as well :)

This question has already been answered. Start a new discussion instead.