Get key from a list of values in dictionary? [duplicate] - python

This question already has answers here:
Get key by value in dictionary
(43 answers)
How to implement an efficient bidirectional hash table?
(8 answers)
Python: How to search a nested list using recursion
(5 answers)
Closed 8 months ago.
Let's say I have:
ref = ['<var>', '<id>', '<expr>']
val = [['a', 'b', 'c'], 'a', '1+1']
dicio = dict(zip(ref, val))
now, I know that by doing
list(dicio.keys())[list(dicio.values()).index('a')]
It returns <id>. But let's say that you only had one value associated per key, so
val = [['a', 'b', 'c'], 'b', '1+1']
How could I get <var> without listing ['a', 'b', 'c']?
Thank you.

Just replace "a" value by the list ['a', 'b', 'c']:
print(list(dicio.keys())[list(dicio.values()).index(['a', 'b', 'c'])])
You will get as output the value associated with the index you inserted before:
<var>
Or you can use list comprehension to traverse the list of dict values:
ref = ['<var>', '<id>', '<expr>']
val = [['a', 'b', 'c'], 'a', '1+1']
dicio = dict(zip(ref, val))
selectedVal = list(i for i in list(dicio.values()) if "a" in i)[0]
print(list(dicio.keys())[val.index(selectedVal)])
Which outputs the same as the previous solution.

Related

Function that takes list input, and returns a new list containing only the elements in that are repeated [duplicate]

This question already has answers here:
How do I find the duplicates in a list and create another list with them?
(42 answers)
Closed 5 months ago.
>>> list_a = ['a', 'b', 'c', 'c']
>>> get_repeated(list_a)
['c']
What would be the most pythonic way to do function get_repeated()?
this should work
from collections import Counter
list_a = ['a', 'b', 'c', 'c']
count = Counter(list_a)
output = [key for key, val in count.items() if val > 1]
print(output)
>>> ['c']

Python : Comprehensions [duplicate]

This question already has answers here:
How to get ordered set? [duplicate]
(2 answers)
Closed 1 year ago.
I have a list :
lis = ['a', 'b', 'c', 'd', 'd', 'e', 'e']
I am trying to use comprehensions to get values which are duplicate.
duplicates = set([x for x in lis if lis.count(x) > 1])
This returns :
{'d','e'}
Now I create a list out of above set :
duplicates = list(set([x for x in lis if lis.count(x) > 1]))
I get output as :
['e', 'd']
Why the order changes?
set does not guarantee the order, dict does.
>> duplicates = dict.fromkeys([x for x in lis if lis.count(x) > 1], None)
>> duplicates = list(duplicates); duplicates
['d', 'e']
That's because Set stores the elements in a random manner.
Try running this code multiple times and see the outputs.
s = {"a","b","g","f"}
print(s)

Python sort list with list.count does not work if list has items of equal occurrence [duplicate]

This question already has answers here:
Python list sort in descending order
(6 answers)
Sort Python list using multiple keys
(6 answers)
Closed 4 years ago.
I have been trying to sort a list of elements (string) according to their occurrence in Python3. I have been using the inbuilt sort() method with the string.count as key as shown below.
p = "acaabbcabac"
print(sorted(p, key=p.count))
# Output : ['c', 'b', 'b', 'c', 'b', 'c', 'a', 'a', 'a', 'a', 'a']
#But expected output is ['a','a','a','a','a','b','b','b','c','c','c']
p = "acaabbcb"
print(sorted(p, key=p.count))
# Output : ['c', 'c', 'a', 'a', 'a', 'b', 'b', 'b']
#Output is as expected
p = "ababab"
print(sorted(p, key=p.count))
# Output :['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
#But expected output is ['a','a','a','b','b','b']
What I have observed is, the above sort works as per the occurrence of the element, but it works only if the counts of each element is different. If the occurrence of any two or more elements is same, then they are listed in the same order they appear in the string/list.
Am I doing something wrong or is there a better approach at this ? I tried searching answers for this issue but I could not find and so am posting this here.
Thanks in advance.
Use a lambda function in your sorting key, where the first operation is p.count, and the second simply sorts on the element value (which ends up being alphabetical):
p = "ababab"
sorted(p, key = lambda x: [p.count, x])
# ['a', 'a', 'a', 'b', 'b', 'b']

Flattening list of lists [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 5 years ago.
Hey I am having trouble trying to make a list of list into just one please help:
I want:
a = [['a'], 'b', 'c', 'd', 'e']
To become:
a = ['a', 'b', 'c', 'd', 'e']
Thanks
As long as your lists can't be nested more than one deep, you could do:
def flatten(lst):
for el in lst:
if isinstance(el, list):
yield from el
else:
yield el
Then call list on the result if you actually need it as a list (usually an iterator will do).
a = [['a'], 'b', 'c', 'd', 'e']
flat_a = flatten(a) # not a list, but an iterator that returns flat values
flat_a_as_lst = list(flat_a) # actually a list
Try to iterate all sub-lists of the list. For your list a:
a = [['a'], 'b', 'c', 'd', 'e']
flat_a = [subitem for item in a for subitem in (item if isinstance(item, list) else [item])]
Edit: considered Adams's comment.

How to combine every element of a list to the other list? [duplicate]

This question already has answers here:
Element-wise addition of 2 lists?
(17 answers)
Closed 5 years ago.
Suppose there are two lists:
['a', 'b', 'c'], ['d', 'e', 'f']
what I want is:
'ad','ae','af','bd','be','bf','cd','ce','cf'
How can I get this without recursion or list comprehension? I mean only use loops, using python?
The itertools module implements a lot of loop-like things:
combined = []
for pair in itertools.product(['a', 'b', 'c'], ['d', 'e', 'f']):
combined.append(''.join(pair))
While iterating through the elements in the first array, you should iterate all of the elements in the second array and push the combined result into the new list.
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
combined_list = []
for i in first_list:
for j in second_list:
combined_list.append(i + j)
print(combined_list)
This concept is called a Cartesian product, and the stdlib itertools.product will build one for you - the only problem is it will give you tuples like ('a', 'd') instead of strings, but you can just pass them through join for the result you want:
from itertools import product
print(*map(''.join, product (['a','b,'c'],['d','e','f']))

Categories