Forum Archive

List = dictionary

AZOM

I’m searching for a way to see if the numbers in a list = the numbers in a dictionary key. EX: dictionary = {12345:6, 01928:7} list = [1, 2, 3]. And the output would be like: the list fit in the key 12345.

cvp

@AZOM not nice, I agree

dict = {'12345':6, '01928':7}
list = [1, 2, 3]

for k in dict.keys():
    ok = True
    for e in list:
        if str(e) not in k:
            ok = False
            break
    if ok:
        print('list in',k)
        break 
cvp

Better

dict = {'12345':6, '1928':7}
lst = [1, 2, 3]

for k in dict.keys():
    if  [x for x in lst if str(x) in k] == lst:
        print('lst in',k)
        break 
pulbrich
dict = {'12345':6, '01928':7}
list = [1, 2, 3]
set_list = set(list)

found = []
for k in dict.keys():
  if set([int(aK) for aK in k]) >= set_list:
    found.append(k)

print(found) 
pulbrich

Or, if readability is not much of a concern:

dict = {'12345':6, '01928':7}
list = [1, 2, 3]

found = [k for k in dict.keys() if set([int(aK) for aK in k]) >= set(list)]
print(found) 
cvp

@pulbrich I like it.

ccc

You almost never need to use dict.keys().

dct = {"12345": 6, "01928": 7}
lst = [1, 2, 3, 12, 34, 234]
print("\n".join(key for key in dct if all(str(i) in key for i in lst)))
AZOM

@ccc
Something I forgot to precise is that the keys in the dictionary are not strings but raw values (without the ā€˜ā€™)