473,404 Members | 2,170 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

get keys with the same values

Hello,

I have a dictionary and will get all keys which have the same values.

d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}

I will something as :

d.keys(where their values are the same)

With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']

Would somebody tell me how I can do it?

Regards,
Nader
Jun 27 '08 #1
13 12735
Nader:
d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
I will something as :
d.keys(where their values are the same)
That's magic.

With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']
Would somebody tell me how I can do it?
You can create a new dict where the keys are the values of the input
dict and the values are a list of the keys of the original dict. So
scanning the keys, values of the input dict, you can fill the second
dict. Then you can scan the second dict, and create a list that
contains only value lists longer than one.

Bye,
bearophile
Jun 27 '08 #2
On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <n.*****@gmail.com>
wrote:
>Hello,

I have a dictionary and will get all keys which have the same values.

d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
That's not a dictionary, it's a syntax error. If you actually
have a dictionary you could say

d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}

dd = {}

for key, value in d.items():
try:
dd[value].append(key)
except KeyError:
dd[value] = [key]

Possibly dd is now what you really want; if you really
want what you said you want you could use

[l for l in dd.values() if len(l) 1]
>I will something as :

d.keys(where their values are the same)

With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']

Would somebody tell me how I can do it?

Regards,
Nader
David C. Ullrich
Jun 27 '08 #3
On Jun 12, 1:35 pm, bearophileH...@lycos.com wrote:
Nader:
d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
I will something as :
d.keys(where their values are the same)

That's magic.
With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']
Would somebody tell me how I can do it?

You can create a new dict where the keys are the values of the input
dict and the values are a list of the keys of the original dict. So
scanning the keys, values of the input dict, you can fill the second
dict. Then you can scan the second dict, and create a list that
contains only value lists longer than one.

Bye,
bearophile
Is it niet possible with one or two statement, maybe with list
comprehension. For exmple:

l = [(k,v) for k in d.keys() for v in d.values() | en here we need
some extra logic (v = 1)]

I don;t konw how we can define a logic statement in a list
comprehension.
It will be very compact, if it would possible.

Nader
Jun 27 '08 #4
On Jun 12, 1:41 pm, David C. Ullrich <dullr...@sprynet.comwrote:
On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <n.em...@gmail.com>
wrote:
Hello,
I have a dictionary and will get all keys which have the same values.
d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}

That's not a dictionary, it's a syntax error. If you actually
have a dictionary you could say

d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}

dd = {}

for key, value in d.items():
try:
dd[value].append(key)
except KeyError:
dd[value] = [key]

Possibly dd is now what you really want; if you really
want what you said you want you could use

[l for l in dd.values() if len(l) 1]
I will something as :
d.keys(where their values are the same)
With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']
Would somebody tell me how I can do it?
Regards,
Nader

David C. Ullrich
Thank for your type about the syntax error. This an example example,
the keys of my dictionary are tuples:
d = {(37.75, 42.22): 1 , (37.51, 40.02): 3 (45.55, 24.27): 4 (47.08,
30.99) : 1}

But what I will is to get all keys which has the same valus. And not
the keys that have value more than 1!

Nader
Jun 27 '08 #5
On Jun 12, 1:48*pm, Nader <n.em...@gmail.comwrote:
On Jun 12, 1:35 pm, bearophileH...@lycos.com wrote:
Nader:
d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
I will something as :
d.keys(where their values are the same)
That's magic.
With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']
Would somebody tell me how I can do it?
You can create a new dict where the keys are the values of the input
dict and the values are a list of the keys of the original dict. So
scanning the keys, values of the input dict, you can fill the second
dict. Then you can scan the second dict, and create a list that
contains only value lists longer than one.
Bye,
bearophile

Is it niet possible with one or two statement, maybe with list
comprehension. For exmple:

l = [(k,v) for k in d.keys() for v in d.values() | en here we need
some extra logic (v = 1)]

I don;t konw how we can define a logic statement in a list
comprehension.
It will be very compact, if it would possible.

Nader
If you are going to use this reverse look-up alot you'd be better off
building another dictionary with the original values being keys and
the original keys being values, if it is used infrequently enough you
can search for it with result_list = [k for k,v in dictionary.items()
if v == search_value]
Jun 27 '08 #6
On Jun 12, 2:05 pm, Chris <cwi...@gmail.comwrote:
On Jun 12, 1:48 pm, Nader <n.em...@gmail.comwrote:
On Jun 12, 1:35 pm, bearophileH...@lycos.com wrote:
Nader:
d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
I will something as :
d.keys(where their values are the same)
That's magic.
With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']
Would somebody tell me how I can do it?
You can create a new dict where the keys are the values of the input
dict and the values are a list of the keys of the original dict. So
scanning the keys, values of the input dict, you can fill the second
dict. Then you can scan the second dict, and create a list that
contains only value lists longer than one.
Bye,
bearophile
Is it niet possible with one or two statement, maybe with list
comprehension. For exmple:
l = [(k,v) for k in d.keys() for v in d.values() | en here we need
some extra logic (v = 1)]
I don;t konw how we can define a logic statement in a list
comprehension.
It will be very compact, if it would possible.
Nader

If you are going to use this reverse look-up alot you'd be better off
building another dictionary with the original values being keys and
the original keys being values, if it is used infrequently enough you
can search for it with result_list = [k for k,v in dictionary.items()
if v == search_value]
Thank you! It is the anwser which I was looking for. [(k,v) for k,v
in d.items() if v is pattern].
But I don't understand what tou mean of "reverse look-up a lot"! I
have to read some informations inclusive (latitudes and longitudes)
form a file and after some processing to save part of this information
to other file.
Why do I make a new dictionary?

Nader
Jun 27 '08 #7
Nader <n.*****@gmail.comwrote:
I have a dictionary and will get all keys which have the same values.

d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}

I will something as :

d.keys(where their values are the same)

With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']

Would somebody tell me how I can do it?
Here's one way:
>>import itertools, functools, operator
d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
get = functools.partial(operator.getitem, d)
for (k,v) in itertools.groupby(sorted(d, key=get), key=get):
print k, list(v)
1 ['a', 'e']
2 ['c']
3 ['b', 'd']
4 ['f']

or if you want a dictionary:
>>dict((k,list(v)) for (k,v) in
itertools.groupby(sorted(d, key=get), key=get))
{1: ['a', 'e'], 2: ['c'], 3: ['b', 'd'], 4: ['f']}

--
Duncan Booth http://kupuguy.blogspot.com
Jun 27 '08 #8
On Jun 12, 2:15*pm, Nader <n.em...@gmail.comwrote:
On Jun 12, 2:05 pm, Chris <cwi...@gmail.comwrote:
On Jun 12, 1:48 pm, Nader <n.em...@gmail.comwrote:
On Jun 12, 1:35 pm, bearophileH...@lycos.com wrote:
Nader:
d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
I will something as :
d.keys(where their values are the same)
That's magic.
With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']
Would somebody tell me how I can do it?
You can create a new dict where the keys are the values of the input
dict and the values are a list of the keys of the original dict. So
scanning the keys, values of the input dict, you can fill the second
dict. Then you can scan the second dict, and create a list that
contains only value lists longer than one.
Bye,
bearophile
Is it niet possible with one or two statement, maybe with list
comprehension. For exmple:
l = [(k,v) for k in d.keys() for v in d.values() | en here we need
some extra logic (v = 1)]
I don;t konw how we can define a logic statement in a list
comprehension.
It will be very compact, if it would possible.
Nader
If you are going to use this reverse look-up alot you'd be better off
building another dictionary with the original values being keys and
the original keys being values, if it is used infrequently enough you
can search for it with result_list = [k for k,v in dictionary.items()
if v == search_value]

Thank you! It is the anwser which I was looking for. [(k,v) for k,v
in *d.items() if v is pattern].
But I don't understand what tou mean of "reverse look-up a lot"! I
have to read some informations inclusive (latitudes and longitudes)
form a file and after some processing to save part of this information
to other file.
Why do I make a new dictionary?

Nader
If you are just going to perform the lookup once or twice then it's
fine to traverse (step through) your original dictionary. If you are
going to look up data often though it might be a better idea to build
another dictionary with the reverse of your original dictionary as it
will yield faster results.

For example, your original dictionary of values is built and then you
perform a handful of operations and move on, then use the list
comprehension to get your data and move on. If, on the other hand,
you build your dictionary and then maybe iterate over a file and need
to look-up the information for every line in the file it would be
better suited to build a new dictionary that transposed the key and
value pairs for less resource intensive and faster operation. eg:

reverse_dict = {}
for k,v in original_dict:
if v in reverse_dict:
reverse_dict[v].append(k)
else:
reverse_dict[v] = [k]

Then once that is built and you want to find which keys in the
original dictionary have the value of "1" you can just do
"list_of_keys = reverse_dict[1]".

Essentially if you are going to do alot of searching for values that
match values found in a dictionary you would be better off to create
the new data structure.

Hope that helps.
Jun 27 '08 #9
On Jun 12, 6:41*am, David C. Ullrich <dullr...@sprynet.comwrote:
On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <n.em...@gmail.com>
wrote:
Hello,
I have a dictionary and will get all keys which have the same values.
<snip>
>
d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}

dd = {}

for key, value in d.items():
* try:
* * dd[value].append(key)
* except KeyError:
* * dd[value] = [key]
<snip>

Instead of all that try/except noise, just use the new defaultdict:
>>from collections import defaultdict

d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}

dd = defaultdict(list)
for key, value in d.items():
... dd[value].append(key)
...
>>for k,v in dd.items():
... print k,':',v
...
1 : ['a', 'e']
2 : ['c']
3 : ['b', 'd']
4 : ['f']

-- Paul
Jun 27 '08 #10
In article
<d4**********************************@p25g2000hsf. googlegroups.com>,
Nader <n.*****@gmail.comwrote:
On Jun 12, 1:41 pm, David C. Ullrich <dullr...@sprynet.comwrote:
On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <n.em...@gmail.com>
wrote:
>Hello,
>I have a dictionary and will get all keys which have the same values.
>d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
That's not a dictionary, it's a syntax error. If you actually
have a dictionary you could say

d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}

dd = {}

for key, value in d.items():
try:
dd[value].append(key)
except KeyError:
dd[value] = [key]

Possibly dd is now what you really want; if you really
want what you said you want you could use

[l for l in dd.values() if len(l) 1]
>I will something as :
>d.keys(where their values are the same)
>With this statement I can get two lists for this example:
>l1= ['a','e']
>l2=['b','d']
>Would somebody tell me how I can do it?
>Regards,
>Nader
David C. Ullrich

Thank for your type about the syntax error. This an example example,
the keys of my dictionary are tuples:
d = {(37.75, 42.22): 1 , (37.51, 40.02): 3 (45.55, 24.27): 4 (47.08,
30.99) : 1}

But what I will is to get all keys which has the same valus.
That's exactly what the code I posted does.
And not
the keys that have value more than 1!
It doesn't do that. Or if you prefer, it doesn't do that!

Instead of looking at it and trying to figure out what it does,
which of course can be tricky, try _running_ the code.
Then print dd. Then print [l for l in dd.values() if len(l) 1] .
>
Nader
--
David C. Ullrich
Jun 27 '08 #11
In article
<3f**********************************@e39g2000hsf. googlegroups.com>,
Paul McGuire <pt***@austin.rr.comwrote:
On Jun 12, 6:41*am, David C. Ullrich <dullr...@sprynet.comwrote:
On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <n.em...@gmail.com>
wrote:
>Hello,
>I have a dictionary and will get all keys which have the same values.
<snip>

d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}

dd = {}

for key, value in d.items():
* try:
* * dd[value].append(key)
* except KeyError:
* * dd[value] = [key]
<snip>

Instead of all that try/except noise, just use the new defaultdict:
That's certainly much better. The machine where I am in
the early morning is still stuck with Python 1.5.3...
>from collections import defaultdict

d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}

dd = defaultdict(list)
for key, value in d.items():
... dd[value].append(key)
...
>for k,v in dd.items():
... print k,':',v
...
1 : ['a', 'e']
2 : ['c']
3 : ['b', 'd']
4 : ['f']

-- Paul
--
David C. Ullrich
Jun 27 '08 #12
Paul McGuire <pt***@austin.rr.comwrote:
Instead of all that try/except noise, just use the new defaultdict:
>from collections import defaultdict

d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}

dd = defaultdict(list)
for key, value in d.items():
... dd[value].append(key)
...
>for k,v in dd.items():
... print k,':',v
...
1 : ['a', 'e']
2 : ['c']
3 : ['b', 'd']
4 : ['f']
Or use the little understood dict.setdefault method which has been
with us from time immemorial...
>>d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
dd = {}
for k, v in d.items():
.... dd.setdefault(v, []).append(k)
....
>>dd
{1: ['a', 'e'], 2: ['c'], 3: ['b', 'd'], 4: ['f']}
>>>
--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jun 27 '08 #13
You could use my mseqdict implementation of a sorted dict.

http://home.arcor.de/wolfgang.grafen...s/Modules.html

swap:
This method can only be applied when all values of the dictionary are
immutable. The Python dictionary cannot hold mutable keys! So swap
doesn't work if only one of the values has the type list or dictionary.
Tuples and instances of classes are save as long as they don't emulate
lists or dictionaries.

from
http://home.arcor.de/wolfgang.grafen...Mseqdict.html:
>>x=seqdict.mseqdict(dict)
x['Bild']='painting'
x['Ziel']='goal'
x['Tor'] ='goal'
x # A small German - English dictionary
mseqdict(
['gewinnen', 'deshalb', 'Abend', 'aber', 'Bild', 'Erkennung',
'Fl\366te', 'Ziel', 'Tor'],
{'Tor': ['goal'], 'Ziel': ['goal'], 'gewinnen': ['gain'], 'deshalb':
['therefore'], 'Abend': ['evening'], 'aber': ['but'], 'Bild':
['picture', 'painting'], 'Erkennung': ['recognition'], 'Fl\366te':
['flute']})
>>x.swap()
x # A small English - German dictionary
mseqdict(
['gain', 'therefore', 'evening', 'but', 'picture', 'painting',
'recognition', 'flute', 'goal'],
{'but': ['aber'], 'recognition': ['Erkennung'], 'painting': ['Bild'],
'flute': ['Fl\366te'], 'gain': ['gewinnen'], 'goal': ['Ziel', 'Tor'],
'evening': ['Abend'], 'therefore': ['deshalb'], 'picture': ['Bild']})

Best regards

Wolfgang
Nader schrieb:
Hello,

I have a dictionary and will get all keys which have the same values.

d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}

I will something as :

d.keys(where their values are the same)

With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']

Would somebody tell me how I can do it?

Regards,
Nader
Jun 27 '08 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Gerrit Holl | last post by:
Hi, is it guaranteed that dict(zip(d.keys(), d.values())) == d? In words, do .keys() and .values() always have the same order? Is it safe to rely on this? yours, Gerrit. --
8
by: Steven Bethard | last post by:
Sorry if this is a repost -- it didn't appear for me the first time. So I was looking at the Language Reference's discussion about emulating container types, and nowhere in it does it mention...
2
by: Pekka | last post by:
Could somebody say why the piece of code below does not work? My purpose is to renumber keys in a SortedList (after removal of an item) so that the keys would always contain an unbroken sequence of...
90
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in...
7
by: ProvoWallis | last post by:
I'm still learning python so this might be a crazy question but I thought I would ask anyway. Can anyone tell me if it is possible to join two dictionaries together to create a new dictionary using...
14
by: vatamane | last post by:
This has been bothering me for a while. Just want to find out if it just me or perhaps others have thought of this too: Why shouldn't the keyset of a dictionary be represented as a set instead of a...
22
by: bearophileHUGS | last post by:
>From this interesting blog entry by Lawrence Oluyede: http://www.oluyede.org/blog/2006/07/05/europython-day-2/ and the Py3.0 PEPs, I think the people working on Py3.0 are doing a good job, I am...
2
by: The.Relinator | last post by:
Hello, I am unable to get the following piece of code to work as desired. The fields valuable seems to contain all values however the vaules variable only contains the first assignied with $values...
12
by: Florian Brucker | last post by:
Hi everybody! Given a dictionary, I want to create a clustered version of it, collecting keys that have the same value: {1:, 2:, 3:} That is, generate a new dict which holds for each value...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.