How to return dictionary keys as a list in Python?
This will convert the dict_keys
object to a list
:
list(newdict.keys())
On the other hand, you should ask yourself whether or not it matters. It is Pythonic to assume duck typing -- if it looks like a duck and it quacks like a duck, it is a duck. The dict_keys
object can be iterated over just like a list
. For instance:
for key in newdict.keys():
print(key)
Note that dict_keys
doesn't support insertion newdict[k] = v
, though you may not need it.
return dictionary keys with the same list values
You can convert values to tuples and use them as a key in temporary dictionary:
Try:
example_dict = {
"list_1": [1, 2, "x"],
"list_2": [1, 3, "x"],
"list_3": [1, 2, "x"],
"list_4": [1, 2, "d"],
"list_5": [1, 3, "x"],
}
out = {}
for k, v in example_dict.items():
out.setdefault(tuple(v), []).append(k)
print(list(v for v in out.values() if len(v) > 1))
Prints:
[['list_1', 'list_3'], ['list_2', 'list_5']]
How to specify a return type for dictionary keys in Python?
For Python 3.9, you can KeysView
from the collections
module to type hint your function:
from collections import KeysView
d = {'1': 1}
def keys(d: dict[str, int]) -> KeysView[str]:
return d.keys()
Docs: https://docs.python.org/3/library/collections.abc.html#collections.abc.KeysView
For older versions, use typing.KeysView
instead.
PYTHON: How to return a dictionary key if a list contains all values for that key
Iterate over your recipes dict and filter to the recipes where you have all the ingredients:
breakfast_recipes = {
"cerealBowl" : ["milk", "cereal"],
"toast" : ["bread", "butter"],
"eggsBacon" : ["eggs", "bacon"],
"frenchToast" : ["bread", "eggs"]
}
def get_recipes(ingredients):
return {
r: i for r, i in breakfast_recipes.items()
if set(ingredients).issuperset(set(i))
}
current_ingredients = ["milk", "bread", "rice", "butter", "eggs"]
print("Meals available to make...")
for r, i in get_recipes(current_ingredients).items():
print(f"{r} with {i}")
Meals available to make...
toast with ['bread', 'butter']
frenchToast with ['bread', 'eggs']
How to change dictionary key value from a list to a single int or float in python?
Just use the dict-comprehension, where you can assign the aggregate value calling the function for the list for each keys.
>>> {k:sum(v) for k,v in ID_TypeDict.items()}
{2: 1.0, 3: 1.0, 4: 2.0}
Return dictionary keys based on list integer value
A dictionary comprehension would provide you what you need.
- You need to make sure the types agree (
int
vs.str
) - Unless the list is significantly longer than the dict, it will be much more efficient to iterate over the list and check that key is in the dict than the other way around.
E.g.:
In []:
new_dict = {k: my_dict[k] for k in map(int, my_list) if k in my_dict}
print(new_dict)
Out[]:
{7777777: '500'}
How to return all dictionary values and keys from function
Assuming data_dict
is a list of dictionaries, let's do the same for resources
, you can do something like:
def __init__(self):
self.resources = []
def get_data(self):
for data in data_dict:
new_dict = {}
new_dict['folder_id'] = data['folder_id']
new_dict['name'] = data['name']
self.resources.append(new_dict)
return self.resources
Python Dictionary: Create a list for all keys in dict, another for all values in dict
Try list(Counter.keys())
and list(Counter.values())
>>> counter= Counter({'firstKey': 1708, 'secondKey': 1589, 'thirdKey': 1424})
>>> Keys = list(counter.keys())
>>> Keys
['firstKey', 'secondKey', 'thirdKey']
>>> Vals = list(counter.values())
>>> Vals
[1708, 1589, 1424]
>>>
Related Topics
Get Rows Based on Distinct Values from One Column
Why Is the Id of a Python Class Not Unique When Called Quickly
Raw_Input Without Pressing Enter
Settingwithcopywarning Even When Using .Loc[Row_Indexer,Col_Indexer] = Value
Python Windows Authentication Username and Password Is Not Working
Pytest - Specify Log Level from the Cli Command Running the Tests
To Read Line from File Without Getting "\N" Appended at the End
Scheduling a Regular Event: Cron/Cron Alternatives (Including Celery)
Get Spotify Currently Playing Track
What Does "The Following Packages Will Be Superseded by a Higher Priority Channel" Mean
How to Set Python's Default Version to 3.X on Os X
Creating a JSON Response Using Django and Python
How to Create a Zip Archive of a Directory
Is _Init_.Py Not Required for Packages in Python 3.3+
How to "Perfectly" Override a Dict
How to Limit Execution Time of a Function Call