Dictionary Comprehension

Run Settings
LanguagePython
Language Version
Run Command
# Type - 1 (SIMPLE LIST COMPREHENSION) student_name = {'charles': 47, 'Nathan': 28, 'Adam': 19} add_value = 92 new_dict = {item: value + add_value for (item, value) in student_name.items()} print(new_dict) # Type - 2 (LIST COMPREHENSION WITH OPERATION) dic_key = ['m','u','t','z','x'] dic_val = [19,67,28,17,15] new_dic = { a:b for (a,b) in zip(dic_key, dic_val)} print (new_dic) # Type - 3 (LIST COMPREHENSION WITH IF condition) my_dict = { 'key_1': {'mouth', 'foot', 'tooth'}, 'key_2': {'John', 'Georgia'}, 'key_3': {'Smith', 'Jonas', 'Denver'} } dict_comp = { key : value for (key, value) in my_dict.items() if len(value) % 2 == 0} print(dict_comp) str = "a12bcd3efg456" alpha_list = [i for i in str if i.isalpha()] print(alpha_list) alpha_str = "".join([i for i in str if i.isalpha()]) print(alpha_str) # Type - 4 (LIST COMPREHENSION WITH IF-ELSE condition) str = "a12bcd3efg456" alpha_num_list = [i.upper() if i.isalpha() else int(i)**2 for i in str] print(alpha_num_list) # Type - 5 (LIST COMPREHENSION WITH NESTED IF conditions) lst = [-2, 10, 5, 3, -1, 0, -15, 6, -30, 12] positive_even_list = [ i for i in lst if i > 0 if i % 2 == 0 ] print(positive_even_list) # Type - 6 (LIST COMPREHENSION WITH NESTED loops) nested_loop_list = [ i for i in range(5) for j in range(i) ] print(nested_loop_list)
Editor Settings
Theme
Key bindings
Full width
Lines