Categories:Viewed: 3 - Published at: a few seconds ago

[ Write a program to convert key-values list to flat dictionary ]

Write a program to convert key-values list to flat dictionary

from itertools import product 
test_dict = {'month' : [1, 2, 3], 
             'name' : ['Jan', 'Feb', 'March']} 

print("The original dictionary is : " + str(test_dict)) 

res = dict(zip(test_dict['month'], test_dict['name'])) 
print("Flattened dictionary : " + str(res)) 

Write a program to remove the duplicate words

s = "Hello world Hello"
l = s.split() 
k = [] 
for i in l: 
    if (s.count(i)>1 and (i not in k)or s.count(i)==1): 
        k.append(i) 
print(' '.join(k)) 

Write a program to convert into dictionary

def Convert(tup, di): 
    for a, b in tup: 
        di.setdefault(a, []).append(b) 
    return di 

tups = [("A", 10), ("B", 20), ("C", 30),  
     ("D", 40), ("E", 50), ("F", 60)] 
dictionary = {} 
print (Convert(tups, dictionary)) 

Write program to extract digits from Tuple list

from itertools import chain 
test_list = [(15, 3), (3, 9), (1, 10), (99, 2)] 
print("The original list is : " + str(test_list)) 
temp = map(lambda ele: str(ele), chain.from_iterable(test_list)) 
res = set() 
for sub in temp: 
    for ele in sub: 
        res.add(ele) 
print("The extrated digits : " + str(res))  

Write a program to Remove Tuples of Length K Using list comprehension

test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)] 
print("The original list : " + str(test_list)) 
K = 1
res = [ele for ele in test_list if len(ele) != K] 
print("Filtered list : " + str(res)) 

Write a program to find Maximum and Minimum K elements in Tuple

test_tup = (5, 20, 3, 7, 6, 8) 
print("The original tuple is : " + str(test_tup)) 
K = 2
test_tup = list(test_tup) 
temp = sorted(test_tup) 
res = tuple(temp[:K] + temp[-K:]) 
print("The extracted values : " + str(res))  

Write a program to get current date and time

import datetime  
current_time = datetime.datetime.now()  

print ("Time now at greenwich meridian is : " , end = "")  
print (current_time)

Write a program to convert time from 12 hour to 24 hour format

def convert24(str1): 

    # Checking if last two elements of time 
    # is AM and first two elements are 12 
    if str1[-2:] == "AM" and str1[:2] == "12": 
        return "00" + str1[2:-2] 

    # remove the AM     
    elif str1[-2:] == "AM": 
        return str1[:-2] 

    # Checking if last two elements of time 
    # is PM and first two elements are 12    
    elif str1[-2:] == "PM" and str1[:2] == "12": 
        return str1[:-2] 

    else: 

        # add 12 to hours and remove PM 
        return str(int(str1[:2]) + 12) + str1[2:8] 

# Driver Code 

print(convert24("08:05:45 PM"))