Python dictionary keys with matching values [duplicate] - python-3.x

This question already has answers here:
Find all Key-Elements by the same Value in Dicts
(4 answers)
Closed 4 years ago.
I have a dictionary like this,
a= { 1:2, 3:4, 4:2, 8:3,7:4,9:3}
I want to find keys that have same values.
My output should be,
b=[ (1,4),(8,9),(3,7)]
How do I do that in a pythonic way.

a = {1:2, 3:4, 4:2, 8:3,7:4,9:3, 5: 2}
valueDict = {}
mulKeys = []
for key, value in a.items():
if valueDict.get(value) == None:
valueDict[value] = [key]
else:
preExisting = valueDict[value]
preExisting.append(key)
valueDict[value] = preExisting
nested_lst_of_tuples = [tuple(l) for l in valueDict.values()]
print(nested_lst_of_tuples)
Note that, for your given question, the output YOU mentioned is wrong.

a={ 1:2, 3:4, 4:2, 8:3,7:4,9:3}
b=set(a.values())
l=[]
for i in b:
l.append(tuple([k for k,v in a.items() if v == i]))
print l # [(1, 4), (8, 9), (3, 7)]
Distinct values in dictionary can be easily obtained using set.
tuple() converts the list into tuple.

Related

How to merge multiple tuples or lists in to dictionary using loops?

Here is my code to merge all tuple in to dictionary,
x = (1,2,3)
y = ('car',"truck","plane")
z=("merc","scania","boeing")
products={}
for i in x,y,z:
products[x[i]]= {y[i]:z[i]}
output:
error:
6 for i in x,y,z:
----> 7 products[x[i]]= {y[i]:z[i]}
8
9 print(products)
TypeError: tuple indices must be integers or slices, not a tuple
Now if i use indexing method inside loop for identifying positions like below code,
for i in x,y,z:
products[x[0]]= {y[0]:z[0]}
print(products)
out:
{1: {'car': 'merc'}}
here, I could only create what I need but only for a specified index how do create a complete dictionary using multiple lists/tuples??
is it also possible to use Zip & map functions?
Use zip to iterate over your separate iterables/tuples in parallel
list(zip(x, y, z)) # [(1, 'car', 'merc'), (2, 'truck', 'scania'), (3, 'plane', 'boeing')]
x = (1, 2, 3)
y = ("car", "truck", "plane")
z = ("merc", "scania", "boeing")
products = {i: {k: v} for i, k, v in zip(x, y, z)}
print(products) # {1: {'car': 'merc'}, 2: {'truck': 'scania'}, 3: {'plane': 'boeing'}}
You should use integer as indices.
x = (1,2,3)
y = ('car',"truck","plane")
z=("merc","scania","boeing")
products={}
for i in range(len(x)):
products[x[i]]= {y[i]:z[i]}
This should solve your problem
To add for above answer, I'm posting a solution using map,
x = (1,2,3)
y = ('car',"truck","plane")
z=("merc","scania","boeing")
products=dict(map(lambda x,y,z:(x,{y:z}),x,y,z))
print(products)

Python: How to use one dictionary to use to decode the other?

Say if I had two dictionaries:
d1 = {'a':1, 'b':2}
d2 = {'a':'b', 'b':'b', 'a':'a'}
How can I use dictionary d1 as the rules to decode d2, such as:
def decode(dict_rules, dict_script):
//do something
return dict_result
decode(d1,d2)
>> {1:2, 2:2, 1:1}
of course it can be written much shorter, but here a version to see the principle:
result_list = list()
result_dict = dict()
for d2_key in d2.keys():
d2_key_decoded = d1[d2_key]
d2_value = d2[d2_key]
d2_value_decoded = d1[d2_value]
result_dict[d2_key_decoded] = d2_value_decoded
# add a tuple to the result list
result_list.append((d2_key_decoded, d2_value_decoded))
the result might be unexpected - because the resulting dict would have entries with the same key, what is not possible, so the key 1 is overwritten:
>>> # equals to :
>>> result_dict[1] = 2
>>> result_dict[2] = 2
>>> result_dict[1] = 1
>>> # Result : {1:1, 2:2}
>>> # therefore I added a list of Tuples as result :
>>> # [(1, 2), (2, 2), (1, 1)]
but as #Patrik Artner pointed out, that is not possible, because already the input dictionary can not have duplicate keys !

How to convert a 3 column tuple without header to a two key single value dictionary in python?

Suppose I have two tuples, say:
l = (water, lily , 6)
m = (history , book, 5)
I want to convert it to a dictionary with 2 keys and a single value.
dict = {(water,lily): 6} {(history, book) : 5}
for the multiple line tuples in python.
How would I accomplish that?
You can use list comprehension.
l = [('water', 'lily' , 6), ('history' , 'book', 5)]
x = {(one, two): three for one, two, three in l}
print(x) # Prints {('water', 'lilly'): 6, ('history', 'book'): 5)}

Group two dimensional list records Python [duplicate]

This question already has answers here:
Python summing values in list if it exists in another list
(5 answers)
Closed 4 years ago.
I have a list of lists (string,integer)
eg:
my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
I'd like to sum the same items and finally get this:
my2_list=[["apple",116],["banana",15],["orange",9]]
You can use itertools.groupby on the sorted list:
from itertools import groupby
my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
my_list2 = []
for i, g in groupby(sorted(my_list), key=lambda x: x[0]):
my_list2.append([i, sum(v[1] for v in g)])
print(my_list2)
# [['apple', 116], ['banana', 15], ['orange', 9]]
Speaking of SQL Group By and pre-sorting:
The operation of groupby() is similar to the uniq filter in Unix. It
generates a break or new group every time the value of the key
function changes (which is why it is usually necessary to have sorted
the data using the same key function). That behavior differs from
SQL’s GROUP BY which aggregates common elements regardless of their
input order.
Emphasis Mine
from collections import defaultdict
my_list= [["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
result = defaultdict(int)
for fruit, value in my_list:
result[fruit] += value
result = result.items()
print result
Or you can keep result as dictionary
Using Pandas and groupby:
import pandas as pd
>>> pd.DataFrame(my_list, columns=['fruit', 'count']).groupby('fruit').sum()
count
fruit
apple 116
banana 15
orange 9
from itertools import groupby
[[k, sum(v for _, v in g)] for k, g in groupby(sorted(my_list), key = lambda x: x[0])]
# [['apple', 116], ['banana', 15], ['orange', 9]]
If you dont want the order to preserved, then plz use the below code.
my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]]
my_dict1 = {}
for d in my_list:
if d[0] in my_dict1.keys():
my_dict1[d[0]] += d[1]
else:
my_dict1[d[0]] = d[1]
my_list2 = [[k,v] for (k,v) in my_dict1.items()]

How to find the number value set to a specific character within a string (without counting) in python [duplicate]

This question already has answers here:
How to find all occurrences of an element in a list
(18 answers)
How to find all occurrences of an element in a list?
(2 answers)
Closed 9 years ago.
I recently got a project in which I need to find all of the indices where a specific character appeared in a string inputted by the user.
For example the user inputs the string "This is a test" and I wanted to find the indices of all the t's in the string I would get 0, 11, 14
I looked through the built in commands and couldn't find anything so it would be a real help to know a method to find this.
Use enumerate and a list comprehension:
st="This is a test"
print([i for i, c in enumerate(st) if c.lower()=='t'])
Or:
print([i for i, c in enumerate(st) if c in 'tT'])
In either case, prints:
[0, 10, 13]
Explanation
First thing that 'makes this work' is that strings are iterable in Python:
>>> st="This is a test"
>>> for c in st:
... print c
...
T
h
i
s
i
s
a
t
e
s
t
Second thing that makes this work is enumerate which adds a count of all the characters in the string as a tuple:
>>> for tup in enumerate(st):
... print tup
...
(0, 'T')
(1, 'h')
(2, 'i')
(3, 's')
(4, ' ')
(5, 'i')
(6, 's')
(7, ' ')
(8, 'a')
(9, ' ')
(10, 't')
(11, 'e')
(12, 's')
(13, 't')
Pulling those two concepts together into a list comprehension produces the result:
[i for i, c in enumerate(st) if c.lower()=='t']
^^^ Produces the tuple of index and character
^ ^ Index, Character
^^^^^^^^^^^ test the character if it is 't'
^ What is wanted - list of indices
Just a straightforward approach as an alternative to a (better) enumerate option:
[range(len(st))[i] for i in range(len(st)) if st[i].lower() == 't']

Resources