cbbcbail
cbbcbail

Reputation: 1771

Last Key in Python Dictionary

I am having difficulty figuring out what the syntax would be for the last key in a Python dictionary. I know that for a Python list, one may say this to denote the last:

list[-1]

I also know that one can get a list of the keys of a dictionary as follows:

dict.keys()

However, when I attempt to use the logical following code, it doesn't work:

dict.keys(-1)

It says that keys can't take any arguments and 1 is given. If keys can't take arguments, then how can I denote that I want the last key in the list?

I am operating under the assumption that Python dictionaries are ordered in the order in which items are added to the dictionary with most recent item last. For this reason, I would like to access the last key in the dictionary.

I am now told that the dictionary keys are not in order based on when they were added. How then would I be able to choose the most recently added key?

Upvotes: 124

Views: 293762

Answers (14)

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24518

One option is to ise last_key, last_val = my_dict.popitem().

popitem() Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order.

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.

Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.

Then, insert the tuple again before returning last_key. Perhaps someday there will be a peekitem() function.

Upvotes: 0

chro
chro

Reputation: 1

To find the last key of dictionary, use for loops with key , pass the loop and print the key,

#print last key 
d1={"one":"first","two":"second","three":"third"}
for key in d1.keys():pass
print(key)

Upvotes: -2

Since python 3.7 dict always ordered(insert order),

since python 3.8 keys(), values() and items() of dict returns: view that can be reversed:

to get last key:

next(reversed(my_dict.keys()))  

the same apply for values() and items()

PS, to get first key use: next(iter(my_dict.keys()))

Upvotes: 43

smart dev
smart dev

Reputation: 9

this will return last element of dictionary:

dictObj[len(dictObj.keys()) - 1]

Upvotes: 0

Bhojani Ali
Bhojani Ali

Reputation: 11

#to find last key:

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

res = list(dict.key())[-1]
print(res)

#to find last value:

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

res = list(dict.values())[-1]
print(res)

Upvotes: 0

root
root

Reputation: 80346

If insertion order matters, take a look at collections.OrderedDict:

An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.


In [1]: from collections import OrderedDict

In [2]: od = OrderedDict(zip('bar','foo'))

In [3]: od
Out[3]: OrderedDict([('b', 'f'), ('a', 'o'), ('r', 'o')])

In [4]: od.keys()[-1]
Out[4]: 'r'

In [5]: od.popitem() # also removes the last item
Out[5]: ('r', 'o')

Update:

An OrderedDict is no longer necessary as dictionary keys are officially ordered in insertion order as of Python 3.7 (unofficially in 3.6).

For these recent Python versions, you can instead just use list(my_dict)[-1] or list(my_dict.keys())[-1].

Upvotes: 67

aldeb
aldeb

Reputation: 6828

It seems like you want to do that:

dict.keys()[-1]

dict.keys() returns a list of your dictionary's keys. Once you got the list, the -1 index allows you getting the last element of a list.

Since a dictionary is unordered*, it's doesn't make sense to get the last key of your dictionary.

Perhaps you want to sort them before. It would look like that:

sorted(dict.keys())[-1]

Note:

In Python 3, the code is

list(dict)[-1]

*Update:

This is no longer the case. Dictionary keys are officially ordered as of Python 3.7 (and unofficially in 3.6).

Upvotes: 138

0x90
0x90

Reputation: 40982

sorted(dict.keys())[-1]

Otherwise, the keys is just an unordered list, and the "last one" is meaningless, and even can be different on various python versions.

Maybe you want to look into OrderedDict.

Upvotes: 8

ravichandra vydhya
ravichandra vydhya

Reputation: 969

In python 3.6 I got the value of last key from the following code

list(dict.keys())[-1]

Upvotes: 18

rahul4data
rahul4data

Reputation: 281

There's a definite need to get the last element of a dictionary, for example to confirm whether the latest element has been appended to the dictionary object or not.

We need to convert the dictionary keys to a list object, and use an index of -1 to print out the last element.

mydict = {'John':'apple','Mat':'orange','Jane':'guava','Kim':'apple','Kate': 'grapes'}

mydict.keys()

output: dict_keys(['John', 'Mat', 'Jane', 'Kim', 'Kate'])

list(mydict.keys())

output: ['John', 'Mat', 'Jane', 'Kim', 'Kate']

list(mydict.keys())[-1]

output: 'Kate'

Upvotes: 1

Matheus
Matheus

Reputation: 11

You can do a function like this:

def getLastItem(dictionary):
    last_keyval = dictionary.popitem()
    dictionary.update({last_keyval[0]:last_keyval[1]})
    return {last_keyval[0]:last_keyval[1]}

This not change the original dictionary! This happen because the popitem() function returns a tuple and we can utilize this for us favor!!

Upvotes: 1

Victor
Victor

Reputation: 1

yes there is : len(data)-1.

For the first element it´s : 0

Upvotes: -5

Eric Cross
Eric Cross

Reputation: 49

There are absolutely very good reason to want the last key of an OrderedDict. I use an ordered dict to list my users when I edit them. I am using AJAX calls to update user permissions and to add new users. Since the AJAX fires when a permission is checked, I want my new user to stay in the same position in the displayed list (last) for convenience until I reload the page. Each time the script runs, it re-orders the user dictionary.

That's all good, why need the last entry? So that when I'm writing unit tests for my software, I would like to confirm that the user remains in the last position until the page is reloaded.

dict.keys()[-1]

Performs this function perfectly (Python 2.7).

Upvotes: 5

Daniel Roseman
Daniel Roseman

Reputation: 599580

It doesn't make sense to ask for the "last" key in a dictionary, because dictionary keys are unordered. You can get the list of keys and get the last one if you like, but that's not in any sense the "last key in a dictionary".

Upvotes: 15

Related Questions