Found 10784 Articles for Python

Get key from value in Dictionary in Python

Pradeep Elance
Updated on 04-Jun-2020 12:19:41

3K+ Views

Python dictionary contains key value pairs. In this article we aim to get the value of the key when we know the value of the element. Ideally the values extracted from the key but here we are doing the reverse.With index and valuesWe use the index and values functions of dictionary collection to achieve this. We design a list to first get the values and then the keys from it.Example Live DemodictA = {"Mon": 3, "Tue": 11, "Wed": 8} # list of keys and values keys = list(dictA.keys()) vals = list(dictA.values()) print(keys[vals.index(11)]) print(keys[vals.index(8)]) # in one-line print(list(dictA.keys())[list(dictA.values()).index(3)])OutputRunning the above code gives ... Read More

Get indices of True values in a binary list in Python

Pradeep Elance
Updated on 04-Jun-2020 12:17:42

596 Views

When a Python list contains values like true or false and 0 or 1 it is called binary list. In this article we will take a binary list and find out the index of the positions where the list element is true.With enumerateThe enumerate function extracts all the elements form the list. We apply a in condition to check of the extracted value is true or not.Example Live DemolistA = [True, False, 1, False, 0, True] # printing original list print("The original list is : ", listA) # using enumerate() res = [i for i, val in enumerate(listA) if val] # ... Read More

Get first index values in tuple of strings in Python

Pradeep Elance
Updated on 04-Jun-2020 12:15:28

267 Views

We have a tuple of strings. We are required to create a list of elements which are the first character of these strings in the tuple.With indexWe design a for loop to take each element and extract the first character by applying the index condition as 0. Then the list function converts it to a list.Example Live DemotupA = ('Mon', 'Tue', 'Wed', 'Fri') # Given tuple print("Given list : " ,tupA) # using index with for loop res = list(sub[0] for sub in tupA) # printing result print("First index charaters:", res)OutputRunning the above code gives us the following result −Given list ... Read More

Get first element with maximum value in list of tuples in Python

Pradeep Elance
Updated on 04-Jun-2020 12:13:20

903 Views

We have a list of tuple. We are required to find out that tuple which was maximum value in it. But in case more than one tuple has same value we need the first tuple which has maximum value.With itemgetter and maxWith itemgetter(1) we get all the value from index position 1 and then apply a max function to get the item with max value. But in case more than one result is returned, we apply index zero to get the first tuple with maximum element in it.Example Live Demofrom operator import itemgetter # initializing list listA = [('Mon', 3), ('Tue', ... Read More

Flatten given list of dictionaries in Python

Pradeep Elance
Updated on 04-Jun-2020 12:10:57

800 Views

We have a list whose elements are dictionaries. We need to flatten it to get a single dictionary where all these list elements are present as key-value pairs.With for and updateWe take an empty dictionary and add elements to it by reading the elements from the list. The addition of elements is done using the update function.Example Live DemolistA = [{'Mon':2}, {'Tue':11}, {'Wed':3}] # printing given arrays print("Given array:", listA) print("Type of Object:", type(listA)) res = {} for x in listA:    res.update(x) # Result print("Flattened object: ", res) print("Type of flattened Object:", type(res))OutputRunning the above code gives us the following ... Read More

First occurrence of True number in Python

Pradeep Elance
Updated on 04-Jun-2020 12:06:18

380 Views

In this article we are required to find the first occurring non-zero number in a given list of numbers.With enumerate and nextWe sue enumerate to get the list of all the elements and then apply the next function to get the first non zero element.Example Live DemolistA = [0, 0, 13, 4, 17] # Given list print("Given list: " ,listA) # using enumerate res = next((i for i, j in enumerate(listA) if j), None) # printing result print("The first non zero number is at: ", res)OutputRunning the above code gives us the following result −Given list: [0, 0, 13, 4, 17] ... Read More

First Non-Empty String in list in Python

Pradeep Elance
Updated on 04-Jun-2020 12:02:25

536 Views

Given a list of strings, lets find out the first non-empty element. The challenge is – there may be one, two or many number of empty strings in the beginning of the list and we have to dynamically find out the first non-empty string.With nextWe apply the next function to keep moving to the next element if the current element is null.Example Live DemolistA = ['', 'top', 'pot', 'hot', ' ', 'shot'] # Given list print("Given list: " ,listA) # using next() res = next(sub for sub in listA if sub) # printing result print("The first non empty string is : ... Read More

Finding relative order of elements in list in Python

Pradeep Elance
Updated on 04-Jun-2020 11:58:49

359 Views

We are given a list whose elements are integers. We are required to find the relative order which means if they are sorted in ascending order then we need to find index of their positions.With sorted and indexWe first sort the entire list and then find out the index of each of them after the sorting.Example Live DemolistA = [78, 14, 0, 11] # printing original list print("Given list is : ", listA) # using sorted() and index() res = [sorted(listA).index(i) for i in listA] # printing result print("list with relative ordering of elements : ", res)OutputRunning the above code gives ... Read More

Find whether all tuple have same length in Python

Pradeep Elance
Updated on 04-Jun-2020 11:57:20

183 Views

In this article we will find out if all the tuples in a given list are of same length.With lenWe will use len function and compare its result to a given value which we are validating. If the values are equal then we consider them as same length else not.Example Live DemolistA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am', 'Maths')] # printing print("Given list of tuples:", listA) # check length k = 3 res = 1 # Iteration for tuple in listA:    if len(tuple) != k:       res = 0       break # Checking if ... Read More

Find top K frequent elements from a list of tuples in Python

Pradeep Elance
Updated on 04-Jun-2020 11:55:30

177 Views

We have a list of tuples. In it we are required to find the top k frequent element. If k is 3 we are required to find the top three elements from the tuples inside the list.With defaultdictWe put the the elements into a dictionary container using defaultdict. Then find out only the elements which satisfy that top k conditions.Example Live Demoimport collections from operator import itemgetter from itertools import chain # Input list initialization listA = [[('Mon', 126)], [('Tue', 768)], [('Wed', 512)], [('Thu', 13)], [('Fri', 341)]] # set K K = 3 #Given list print("Given list:", listA) print("Check value:", K) ... Read More

Advertisements