简体   繁体   中英

Dictionary comprehension to find all numbers b/w 1 and 25 that are divisible by a single digit other than 1 (2-9)

d={k:v for k in range(1,25) for v in range(2,9) if k%v==0}
print (d)
d={newdic.setdefault(key,value) for key in range(1,25) for value in range(2,9) if key%value==0}
print (newdic)

output of above code is

{2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 3, 10: 5, 12: 6, 14: 7, 15: 5, 16: 8, 18: 6, 20: 5, 21: 7, 22: 2, 24: 8}
{2: 2, 3: 3, 4: 2, 5: 5, 6: 2, 7: 7, 8: 2, 9: 3, 10: 2, 12: 2, 14: 2, 15: 3, 16: 2, 18: 2, 20: 2, 21: 3, 22: 2, 24: 2}

what I am looking for is:

{2: 2, 3: 3, 4: 2, 5: 5, 6: 2, 7: 7, 8: 2, 8: 4, 8: 8, 9: 3, 9: 9, 10: 2, 10: 5,  12: 2, 12: 3, 12: 4, ...}

basically I want the result set to include each number which is divisible by numbers <9. Example : since 8 is divisible by 2,4 and 8, it has 3 entries in there.

Dictionary keys must be unique in Python, however, you can hash a list of all the numbers that divide the key:

final_dict = {i:[b for b in range(2, 10) if i%b == 0] for i in range(2, 25)}
final_dict = {a:b[0] if len(b) == 1 else b for a, b in final_dict.items() if b}

Output:

{2: 2, 3: 3, 4: [2, 4], 5: 5, 6: [2, 3, 6], 7: 7, 8: [2, 4, 8], 9: [3, 9], 10: [2, 5], 12: [2, 3, 4, 6], 14: [2, 7], 15: [3, 5], 16: [2, 4, 8], 18: [2, 3, 6, 9], 20: [2, 4, 5], 21: [3, 7], 22: 2, 24: [2, 3, 4, 6, 8]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM