How to sort dictionary by pseudo-compound key? - python

I have a dictionary:
test = {}
test[(1,2)] = 1
test[(4,3)] = 1
test[(1,4)] = 1
How to sort by "pseudo compound key": first element of tuple and after second element of tuple ?

test = {}
test[(1,2)] = 1
test[(4,3)] = 2
test[(1,4)] = 3
print sorted(test.iteritems())
Will give you:
[((1, 2), 1), ((1, 4), 3), ((4, 3), 2)]
If you want them back as a dictionary:
import OrderedDict
sorted_test = OrderedDict(sorted(test.iteritems()))
You've got a dictionary sorted by it's keys.
This all works because by default, tuples sort as you described.

Dictionaries cannot be sorted by definition. What you can do is get the list of keys, sort it, and then refer to the dictionary in given order. For example:
test = {}
test[(1,2)] = 1
test[(4,3)] = 2
test[(1,4)] = 3
keys = sorted(test.keys()) # nothing fancy, default sort
for key in keys:
print test[key]
>>> 1
>>> 3
>>> 2

It depends on exactly what you want. If you want the keys of test sorted in that order, all you need is
sorted(test)
If you want the values of the sorted keys, then do
[test[key] for key in sorted(test)]

Related

How to check if tuple key contains an element in dictionary

I am looking for an operation that could do something similar to this:
dict[ ( tuple[0] , _ ) ]
The dictionary contains tuples as keys.
How do I check if the dictionary contains a value where the tuple key has a specific value as the first part and any value as the second part?
Try this,
#Dictionary with tuples as keys
dict_with_tup = dict([((1,2),3), ((1,4),2), ((2,5),7)])
#value that you wanna find (just the first value of the tuple)
x = 1
#filtered dict based on that value
{k:v for k,v in dict_with_tup.items() if k[0]==x}
{(1, 2): 3, (1, 4): 2}
for a dictionary d
x = # value of interest
for key in d.keys():
if key[0] == x:
#do stuff
but as khelwood noted in the comments, it's not a very efficient way of doing things

Obtaining key's index in python dictionary/hash table

I'm trying to obtain the key's index. Let's say i have:
Jamie: 3
Alan: 5
Dwayne: 4
and the keys are the names and values are the digits. What i want now is accessing the key's index in this case, the key Jamie is at index 0, Alan at 1 and Dwayne at 2.
I'm not familiar with this as I'm more used to obtaining the index from a normal list.
Do i do something like:
for i, value in enumerate(dict):
if dict[i] != ...
It doesn't seemed right and i'll appreciate some feedback on this.
As mentioned since dict doesn't store key,value pair in order by default, you will need to convert to orderedDict as below
>>> from collections import OrderedDict
>>> d = OrderedDict(d)
>>> d
OrderedDict([('Jamie', 3), ('Dwayne', 4), ('Alan', 5)])
After that dict's key index will be ordered
>>> d.keys()
['Jamie', 'Dwayne', 'Alan']
Then you can either use
>>> d.keys().index('Alan')
2
OR enumerate method that your are trying. ( Need to add iterator there)
>>> for i,value in enumerate(d.iteritems()):
print i,value
0 ('Jamie', 3)
1 ('Dwayne', 4)
2 ('Alan', 5)
>>>
Here you can access individual key,value as a 0,1 index of tuple.
>>> for i,value in enumerate(d.iteritems()):
print i, value[0], value[1]
0 Jamie 3
1 Dwayne 4
2 Alan 5
>>>
Are you looking for
for key in dict:
if key != ...
and you can use dict[key] to get corresponding value if the statement is met

Check if something in a dictionary is the same as the max value in that dictionary?

How can I check if something in a dictionary is the same as the max in that dictionary. In other words, get all the max values instead of the max value with lowest position.
I have this code which returns the max variable name and value:
d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark, 'g_codww2': g_codww2, 'g_bfront2': g_bfront2, 'g_reddead2': g_reddead2, 'g_fifa18': g_fifa18, 'g_motogp17': g_motogp17, 'g_elderscrolls': g_elderscrolls, 'g_crashbandicoot': g_crashbandicoot}
print("g_dirt4", g_dirt4, "g_destiny2", g_destiny2, "g_southpark", g_southpark, "g_codww2", g_codww2, "g_bfront2", g_bfront2, "g_reddead2", g_reddead2, "g_fifa18", g_fifa18, "g_motogp17", g_motogp17, "g_elderscrolls", g_elderscrolls, "g_crashbandicoot", g_crashbandicoot)
print (max(d.items(), key=lambda x: x[1]))
Now it prints the variable with the highest value plus the value itself, but what if there are two or three variables with the same max value? I would like to print all of the max values.
Edit:
The user has to fill in a form, which adds values to the variables in the dictionary. When the user is done, there will be one, two or more variables with the highest value. For example, the code gives me this:
2017-06-08 15:05:43 g_dirt4 9 g_destiny2 8 g_southpark 5 g_codww2 8 g_bfront2 8 g_reddead2 7 g_fifa18 8 g_motogp17 9 g_elderscrolls 5 g_crashbandicoot 6
2017-06-08 15:05:43 ('g_dirt4', 9)
Now it tells me that g_dirt4 has the highest value of 9, but if you look at motogp17, it also had 9 but it doesn't get printed because it's at a higher position in the dictionary. So how do I print them both? And what if it has 3 variables with the same max value?
Given a dictionary
d = {'too': 2, 'one': 1, 'two': 2, 'won': 1, 'to': 2}
the following command:
result = [(n,v) for n,v in d.items() if v == max(d.values())]
yields: [('too', 2), ('two', 2), ('to', 2)]
Let me introduce you to a more complicated but more powerful answer. If you sort your dictionary items, you can use itertools.groupby for some powerful results:
import itertools
foo = {"one": 1, "two": 2, "three": 3, "tres": 3, "dos": 2, "troi": 3}
sorted_kvp = sorted(foo.items(), key=lambda kvp: -kvp[1])
grouped = itertools.groupby(sorted_kvp, key=lambda kvp: kvp[1])
The sorted line takes the key/value pairs of dictionary items and sorts them based on the value. I put a - in front so that the values will end up being sorted descending. The results of that line are:
>>> print(sorted_kvp)
[('tres', 3), ('troi', 3), ('three', 3), ('two', 2), ('dos', 2), ('one', 1)]
Note, as the comments said above, the order of the keys (in this case, 'tres', 'troi', and 'three', and then 'two' and 'dos', is arbitrary, since the order of the keys in the dictionary is arbitrary.
The itertools.groupby line makes groups out of the runs of data. The lambda tells it to look at kvp[1] for each key-value pair, i.e. the value.
At the moment, you're only interested in the max, so you can then do this:
max, key_grouper = next(grouped)
print("{}: {}".format(max, list(key_grouper)))
And get the following results:
3: [('tres', 3), ('troi', 3), ('three', 3)]
But if you wanted all the information sorted, instead, with this method, that's just as easy:
for value, grouper in grouped:
print("{}: {}".format(value, list(grouper)))
produces:
3: [('tres', 3), ('troi', 3), ('three', 3)]
2: [('two', 2), ('dos', 2)]
1: [('one', 1)]
One last note: you can use next or you can use the for loop, but using both will give you different results. grouped is an iterator, and calling next on it moves it to its next result (and the for loop consumes the entire iterator, so a subsequent next(grouped) would cause a StopIteration exception).
You could do something like this:
max_value = (max(d.items(), key=lambda x: x[1]))[1]
max_list = [max_value]
for key, value in d.items():
if value == max_value:
max_list.append((key, value))
print(max_list)
This will get the maximum value, then loop through all the keys and values in your dictionary and add all the ones matching that max value to a list. Then you print the list and it should print all of them.

Remove duplicate values from a defaultdict python

I have a dictionary.
a = {6323: [169635, 169635, 169635], 6326: [169634,169634,169634,169634,169634,169634,169638,169638,169638,169638], 6425: [169636,169636,169636,169639,169639,169640]}
How do I remove the duplicate values for each key in dictionary a? And make the values become [value, occurrences]?
The output should be
b = {6323: [(169635, 3)], 6326: [(169634, 6), (19638, 4)], 6425: [(169636, 3), (19639, 2), (19640, 1)]}.
EDIT:
Sorry, I pasted the dict.items() output so they weren't dictionaries. I corrected it now.
Also edited the question to be more clear.
I would suggest iterating on the items and for each value build a defaultdict incrementing the occurence. Then convert that indo your tuple list (with the item method) and drop that in the output dictionnary.
b = {}
for k,v in a.items():
d = defaultdict(int)
for i in v:
d[i] += 1
b[k] = d.items()

Adding the values of a dictionary to a list

Hi I am having a bit of difficulty adding tuples which are the values of a dictionary I have extracted the tuples and need to added to an iterable item say an empty list. i.e.
path = [1,2,3,4]
pos = {1:(3,7), 2(3,0),3(2,0),4(5,8)}
h = []
for key in path:
if key in pos:
print pos[key]
h.append(pos[Key])#Gives an error
Please how can i append the values in pos[key] into a h. Thanks
You can use list comprehension:
h = [pos[key] for key in path if key in pos]
Demo:
print h
>>> [(3, 7), (3, 0), (2, 0), (5, 8)]
Notes:
A dictionary should be declared like pairs of key:value. Your syntax is incorrect.
Also, Python is case-sensitive so key is different than Key.

Categories