Reverse entire dictionary items [duplicate] - python-3.x

This question already has answers here:
How do I sort a dictionary by key?
(32 answers)
How do I sort a dictionary by value?
(34 answers)
Closed 2 years ago.
I know this may be a simple question but I'm having trouble reversing my dictionary. All the solutions I've seen haven't been working for me. I have a dictionary where the keys are strings and the values are either None or type int. I want to reverse the order so the last (key, value) pair is first and vice versa.
For example:
d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD: None}
I want to reverse the dictionary to:
reversed_d = {"pointD": None, "pointC": None, "pointB": 140, "pointA": 100}
I've tried sorted(d.items(), reverse=True) and reversed(sorted(d.items()))
but I got an error of:
TypeError: '<' not supported between instances of 'int' and 'str'

You could do it this way.
Loop =>
for k,v in reversed(list(d.items())):
or just
reversed_d = reversed(list(d.items()))

since dictionaries are ordered by insertion order of the keys (since python 3.6, guaranteed since python 3.7), you can reverse the keys:
d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD": None}
for k in reversed(d):
print(k)
From there, you can build a new dictionary by inserting key values in the reversed order, or create a generator to access the (Key, value) pairs in that order.

Related

Query on Slicing a list in Python [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 5 days ago.
How do I print the reverse of a specific selection of a list ?
For example, I have a list,
a = [11,22,33,44,55,66,77,88]
I expect a[1:4:-1] to print [44,33,22], but it gives an empty list.
I have seen Understanding slicing, but I couldn't find an answer.
The python slicing syntax, when 3 parameters are provided, is [start:stop:step]
In order to get the value [44, 33, 22], you'd need to write the slice like this: a[3:0:-1]
This works because the slice starts at index 3, which has a value of 44, and the slice stops before index 0, meaning the last included index is 1 (with a value of 22), based on the step value of -1.

using bisect with tuples in python

I am trying to understand the use of bisect function in the python's bisect module and how to use it with tuples. I have seen that it takes a list and a value to find the index to place the value. In my case the value is a tuple. This is from leetcode 981 https://leetcode.com/problems/time-based-key-value-store/. A is a list of tuple and the tuple will contain (int,string) as its data.
class TimeMap(object):
def __init__(self):
self.M = collections.defaultdict(list)
def set(self, key, value, timestamp):
self.M[key].append((timestamp, value))
def get(self, key, timestamp):
A = self.M.get(key, None)
if A is None: return ""
i = bisect.bisect(A, (timestamp, chr(127)))
return A[i-1][1] if i else ""
I understand what they are trying to do for solving the question . I just want to understand why use chr(127). I tried using None but it gives an error. I am guessing that it will always take the first int value in the tuple because the chr(127) will always be unqualified somehow for bisect to accept. But I am not able to find the correct reason for this. also IDLE shows chr(127) as \x7f and found out its a non ascii character.
Python compares tuples element by element and from left to right. For example:
(1, 2) > (1, 1) is True
(1, 2) > (1, 2) is False
I guess, they use chr(127), to make the second item in the tuple larger than any other character.
(1, chr(127)) > (1, 'z') is True
finally found some understanable solution in leetcode discussion forum. all credits go to leetcode users
https://leetcode.com/slvher/ and https://leetcode.com/jcodem/
The ascii code range of lower char is [97, 122], thus chr(127) can be used to make sure the located index from bisect.bisect(A, (timestamp, chr(127))) can satisfy the condition: timestamp_prev <= timestamp. In fact, chr(ascii_v) can also be used here where ascii_v's range is [123, 127].

Sorting a list of strings items from an array [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 3 years ago.
I'm new to python automation and wrote a script to get some port handles from Ixia and store into a list. I;m trynig to sort that port-handle where I see a problem.
I tried using the sort method but doesn;t work
>>> a
['1/1/11', '1/1/6']
>>> a.sort()
>>> a
['1/1/11', '1/1/6']
>>> d = a.sort()
>>> print(d)
None
>>>
Am i missing anything here .. kindly clarify
I want the output in the following format
1/1/6 1/1/11
Explanation
You are trying to sort a list of strings. Strings are naturally sorted in lexicographical_order, i.e. "10" < "11" < "2" < "5" < ..., so Python executes correctly what you want it to do. This being said, you need to transform your data into something that will be sorted as you want.
Solution
>>> a = ['1/1/11', '1/1/6']
>>> a
['1/1/11', '1/1/6']
>>> def to_tuple(string_representation):
... return tuple(int(i) for i in string_representation.split('/'))
...
>>> b = [to_tuple(element) for element in a]
>>> b.sort()
>>> b
[(1, 1, 6), (1, 1, 11)]
>>> a.sort(key=to_tuple)
>>> a
['1/1/6', '1/1/11']
Here we use the fact that tuple is sorted by default exactly how we want it to be sorted in your case (actually, it is also a lexicographical order, but now 11 is one element of a sequence and not two).
List b contains a transformed list, where each element is a tuple. And now sort will work as you want.
The second option, will be using a custom key operator. It is a function that returns a key to compare different elements of your list. In this case, key will be a corresponding tuple of integers and will be compared as you want.
Note 1
The second approach (with the key operator) will create an additional overhead during sorting as it will be called O(NlogN) times.
Note 2
You also tried using the result of sort function as a value, but it changes the given list in-place. If you want a sorted copy of your list, use sorted.

Python - Iterating Variable in Dictionary - TypeError: 'int' object is not subscriptable

The code worked in Python 2, but not in Python 3 and getting:-
TypeError:
'int' object is not subscriptable
Trying to get the length on the dictionary key while going through the loop.
The loop is iterating through each key and seeking to do things before max is reached and when it reaches max. Looking for guidance on why the TypeError and help.
Here is example dictionary with keys: 1, 2, 3.
my_dict = {1: a, 2: b, 3: c}
Setting int with name max because something needs to happen
max = 3
Python 3
hists = list(my_dict.copy().keys())
for hist in hists:
if len(hist[0]) < max - 1: # <-- TypeError: 'int' object is not subscriptable)
print("pass")
elif len(hist[0]) == max:
print("equal max")
Python 3, we need to lock the keys, protecting iteration of key order and doing this by copying to new dictionary. Because python 3 .keys() returns an iterable view , not like python 2. To get the keys in order, we need to convert to a list, which seems to also set the order.
In Python 2, order is set when using .key() and didn’t need to be concern about views. Common to use dictionary keys in loops.
It's ok to use when the dictionary is not being updated in real-time. Found it tends to be more expensive and slower.
When you do hist in hists, you are getting the actual element, not the index. So for your example, hists will have [1,2,3] and hist variable will have 1,2 and 3 value. And 1[0] will obviously give you an error because 1 is an int, and you can't subscript an int. And you don't have to worry about max, that would have been a problem in a while loop, not for a loop.
To iterate over the dictionary, when you're not deleting or adding new keys is to simply do the following
for key in my_dict:
curr_val = my_dict[key] #This will give you the value at key
And if you only want to find max key then this can be done rather easily
max_key = max(list(my_dict))

Python: Is there any way to sort a dictionary by integer value

Is there any way to find value number in a dictionary, say 3, without knowing the key in python?
I do know that dictionaries do not have an order.
All i can get are arbitrary elements using
dict[dict.keys()[0]]
Thanks in advance.
So, if i understand correctly, you are looking for all keys with the value 3. That can be achieved by itering through the keys and comparing:
output = []
for key, value in dict.items():
if value == 3:
output.append((key, value))
print(output)
If you wanna simply sort by integer values, try:
sorted(dict.items(), key=lambda i:i[1])

Resources