If you are allowed to assume that there are no duplicates in the dict values, then you could invert the dict:
my_dict = {
'A': 250,
'B': 270,
'C': 240
}
my_list = [270, 250, 240]
inverse_dict = dict([(val, key) for key, val in my_dict.items()])
output = [inverse_dict[key]
for key in my_list
]
my_dict = {
'A': 250,
'B': 270,
'C': 240
}
my_list = [270, 250, 240]
def getKey(value):
for key, val in my_dict.items():
if (val == value):
return key
answer = list(map(getKey, my_list))
print(answer)
If you just want to sort the dictionary, you don't need that extra list. You can just do this:
my_dict = {
'A': 250,
'B': 270,
'C': 240
}
ordered = dict(sorted(my_dict.items(), reverse = True, key = lambda item: item[1]))
answer = list(ordered.keys())
print(answer)
First, invert the dictionary using dictionary comprehension. Then use list comprehension to get the desired list:
inv_dict = {
y: x
for x,
y in my_dict.items()
}
new_list = [inv_dict[x]
for x in my_list
]
print(new_list)
#['B', 'A', 'C']
In one line:
new_list = list(dict(sorted({ v: k for k, v in my_dict.items() }.items(), reverse = True)).values())
my_dict = {
'A': 250,
'B': 270,
'C': 240
}
my_list = [270, 250, 240]
answer = []
for num in my_list:
for key, value in my_dict.items():
if num == value:
answer.append(key)
Code Syntax
my_dict = {
'A': 250,
'B': 270,
'C': 240
}
my_list = [270, 250, 240]
def valKey(dict, list):
return [key
for val in list
for key, value in dict.items() if val == value
]
print(valKey(my_dict, my_list))
Output
['B', 'A', 'C']
[Program finished]
Create a new dictionary with keys from seq and values set to value.,For key key, returns value or default if key not in dictionary,Returns true if key in dictionary dict, false otherwise,Similar to get(), but will set dict[key]=default if key is not already in dict
#!/usr/bin/python dict = { 'Name': 'Zara', 'Age': 7, 'Class': 'First' } print "dict['Name']: ", dict['Name'] print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result −
dict['Name']: Zara
dict['Age']: 7
#!/usr/bin/python dict = { 'Name': 'Zara', 'Age': 7, 'Class': 'First' } print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result −
dict['Age']: 8
dict['School']: DPS School
#!/usr/bin/python dict = { 'Name': 'Zara', 'Age': 7, 'Class': 'First' } del dict['Name']; # remove entry with key 'Name' dict.clear(); # remove all entries in dict del dict; # delete entire dictionary print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School']
Python’s dictionary allows you to store key-value pairs, and then pass the dictionary a key to quickly retrieve its corresponding value. Specifically, you construct the dictionary by specifying one-way mappings from key-objects to value-objects. Each key must map to exactly one value, meaning that a key must be unique.,Assume we are working with a dictionary whose values are all unique numbers. Write a function that returns the key that maps to the largest value in the dictionary.,Dictionary Basics Constructing a dictionary Retrieving a value, given a key Adding more key-value mappings ,You can also use dict as a constructor to create the dictionary. It can be fed an iterable of key-value pairs, each of which is packed in a sequence, such as a tuple.
# use a dictionary to map groceries to prices: item - name - > price >>>
items_to_prices = {
"cheese": 2.53,
"milk": 3.40,
"frozen pizza": 8.01
}
# looking up the price of "frozen pizza" >>>
items_to_prices["frozen pizza"]
8.01
# keep track of whether or not a 3 D coordinate fell into some region in space
# map(x, y, z) coordinates to "is in a region": (x, y, z) - > True / False >>>
point_to_region = {
(0.1, 2.2, 3): False,
(-10., 0, 4.5): True,
(4.3, 1.0, 9.5): False
} >>>
point_to_region[(-10., 0, 4.5)]
True
# map student - name to exam scores: name - > scores >>>
name_to_scores = {
"Ryan S": [65, 50, 80],
"Nick S": [100, 99, 90]
} >>>
name_to_scores["Ryan S"]
[65, 50, 80]
>>> type(items_to_prices) dict
# use `{key1:value1, key2:value2, ...} to create a dictionary that maps: # "apple" -> "fruit" # "carrot" -> "vegetable >>> fruit_or_veggie = {"apple":"fruit", "carrot":"vegetable"} # create an empty dictionary >>> {} {}
# use `dict` to create a dictionary that maps: # "apple" - > "fruit" # "carrot" - > "vegetable >>> fruit_or_veggie = dict([("apple", "fruit"), ("carrot", "vegetable")]) # use `dict` to create an empty dictionary: >>> dict() {}
{key:value for key, value in <iterable of key-value pairs> [if bool(<condition>)]}
September 26, 2021February 22, 2022
Let’s create a dictionary called ages
, which, well, contains the ages of different people:
ages = {
'Matt': 30,
'Katie': 29,
'Nik': 31,
'Jack': 43,
'Alison': 32,
'Kevin': 38
}
We can then access a dictionary item, either by using []
square bracket notation or, better yet, using the .get()
dictionary method. Let’s see how we can get the age for Nik
:
>> print(ages.get('Nik'))
31
Let’s see how it works with a list, before diving into a more complex example with a Python dictionary:
some_list = [30, 29, 31, 43, 32, 38] max_value = max(some_list) print(max_value) # Returns: 43
Let’s take a look!
max_value = max(ages.values()) print(max_value) # Returns: 43
We can use the .get()
method we covered earlier to get the max value of a dictionary in Python. You may recall, from the earlier recap of Python dictionaries, that the .get()
method is used to return the value for a key. Let’s see what applying this function to our key=
parameter does:
ages = { 'Matt': 30, 'Katie': 29, 'Nik': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38 } max_value = max(ages, key = ages.get) print(max_value) # Jack