user491
user491

Reputation: 175

Python - Select first first key-value pair from dictionary when it contains duplicate keys

I am converting lists to dictionary...the dictionary may contain duplicate key value pairs. Python Dictionary returns key value pairs based on the last occurrence in the input data. How can i take first key-value pairs from the dictionary when a key repeats multiple times?

i see one solution as mentioned in following link, i need to create list of values for key and then take first element from the values list. List of values for duplicate keys in dictionary Python

Is there any other better way to do this?

Upvotes: 1

Views: 729

Answers (1)

Karin
Karin

Reputation: 8610

You can just iterate through your list backwards using reversed when constructing the dictionary. The constructed dictionary will then only contain the first values of the original list.

Upvotes: 4

Related Questions