0
houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}

what I need is to check and then find 20 for example.

been trying for hours.
would be great if you could provide and explanation and multiple solutions.
thanks in advance.

nightroad
  • 75
  • 1
  • 2
  • 6
  • `print(20 in houses['others'])` ? – Nir Alfasi Mar 29 '17 at 03:34
  • You could use `any`: `any(20 in v for k, v in houses.items()` – Arthur Tacca Mar 29 '17 at 15:56
  • I missed a close bracket in my last comment, it should be: `any(20 in v for k, v in houses.items())` – Arthur Tacca Mar 29 '17 at 16:13
  • thank you alfasin. it works. but can I not find what I want in general?. what if I don`t know that 20 is in another list in the dictionary?. – nightroad Mar 29 '17 at 18:09
  • @ArthurTacca it does't work consistently. once I get a True and the next I get `TypeError: argument of type 'int' is not iterable`. – nightroad Mar 29 '17 at 18:49
  • @nightroad I didn't notice that some of the values are just lone values. I've posted an answer that takes it into account. But if you control the code that builds `houses` in the first place, I suggest you make all the values lists, even if they only have one item in them, and use the code in my earlier comment; that would be cleaner. – Arthur Tacca Mar 30 '17 at 11:06

2 Answers2

1

Your houses is a dictionary. It is missing a } though. Its others key is a list, so you can access its first item like so: print (houses['others'][0]). If you need to iterate over the keys and values, there are several ways as demonstrated in this link:Iterating over dict values . A basic version is like this:

houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}
bool = False
for (k,v) in houses.items():
    if type(v)==list:
        if 20 in v:
            bool = True
            print(k,v)
    if v == 20:
        bool = true
        print(k,v)
print(bool)
Community
  • 1
  • 1
Treefish Zhang
  • 1,131
  • 1
  • 15
  • 27
  • the braces is already in my code. just missed it here. but thank you. adding [0] is't helpful tho, because I need to find the data before I know where is its location. – nightroad Mar 29 '17 at 18:07
  • Dictionary keys and values can be accessed like in this link: https://www.codecademy.com/en/forum_questions/50721fce7c7091000201e56a where the author 'flatten a list using a listcomp with two 'for'' : https://docs.python.org/3/tutorial/datastructures.html – Treefish Zhang Mar 29 '17 at 19:38
0

This will look over all the entries in houses, and look for search in the values. For each value, if it's not a collection, it will compare directly.

def is_in_house(search, house):
    for v in houses.values():
        try:
            if search in v:
                return True
        except TypeError:
            if v == search:
                return True
    return False
Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49