Code:
def getitems(obj): def getkeys(obj, stack): for k, v in obj.items(): k2 = ([k] if k else []) + stack # don 't return empty keys if v and isinstance(v, dict): for c in getkeys(v, k2): yield c else: # leaf yield k2 def getvalues(obj): for v in obj.values(): if not v: continue if isinstance(v, dict): for c in getvalues(v): yield c else: # leaf yield v if isinstance(v, list) else [v] return list(getkeys(obj, [])), list(getvalues(obj))
Input:
{
"shortshirt": {
"ralphlauren": {
"classic": [
"That Ralph Lauren classic fit is a timeless look!",
"Nice choice. Can't go wrong with Ralph Lauren"
]
}
},
"socks": {
"": {
"": ["Have to find the right socks to keep your feet cozy"]
}
}
}
Output:
# keys
[['classic', 'ralphlauren', 'shortshirt'], ['socks']]
# values
[['That Ralph Lauren classic fit is a timeless look!', "Nice choice. Can't go wrong with Ralph Lauren"], ['Have to find the right socks to keep your feet cozy']]
August 30, 2021February 22, 2022
Get all values from nested dictionary
def get_values(d):
for v in d.values():
if isinstance(v, dict):
yield from get_values(v)
else:
yield v
a = {
4: 1,
6: 2,
7: {
8: 3,
9: 4,
5: {
10: 5
},
2: 6,
6: {
2: 7,
1: 8
}
}
}
print(list(get_values(a)))
Here is code that would print all team members:
Liverpool = {
'Keepers': {
'Loris Karius': 1,
'Simon Mignolet': 2,
'Alex Manninger': 3
},
'Defenders': {
'Nathaniel Clyne': 3,
'Dejan Lovren': 4,
'Joel Matip': 5,
'Alberto Moreno': 6,
'Ragnar Klavan': 7,
'Joe Gomez': 8,
'Mamadou Sakho': 9
}
}
for k, v in Liverpool.items():
for k1, v1 in v.items():
print(k1)
Iterates through the elements of the list and checks the type of each element based on the ‘id‘ and ‘children‘ naming convention.
mylist = [{
u 'id': 5650,
u 'children': [{
u 'id': 4635
},
{
u 'id': 5648
}
]
},
{
u 'id': 67,
u 'children': [{
u 'id': 77
}]
}
]
def extract_id_values(mylist):
ids_to_return_list = []
for element in mylist:
for key, value in element.items():
if 'id' == key:
ids_to_return_list.append(value)
if 'children' == key:
for children_elem in value:
if 'id' in children_elem:
ids_to_return_list.append(children_elem['id'])
return ids_to_return_list
print(extract_id_values(mylist))
Using list comprehension + items()
test_dict = { 'Gfg': { "a": 7, "b": 9, "c": 12 }, 'is': { "a": 15, "b": 19, "c": 20 }, 'best': { "a": 5, "b": 10, "c": 2 } } # initializing key key = "a" # using item() to extract key value pair as whole res = [val[key] for keys, val in test_dict.items() if key in val ] print(res)
We can also create a list of keys from the iterable sequence returned by dict.keys() function. Then we print all the items of the list (all keys of the dictionary). For example,,We iterated over all keys of a nested dictionary and printed them one by one. If you want to get all keys of a nested dictionary as a list, then you can just put the values yielded by the the function all_keys() to a list. For example,,We can also use this list comprehension to iterate over all the keys of dictionary and then print each key one by one. For example,,We learned ways to print all keys of a dictionary, including the nested dictionaries.
In Python, the dictionary class provides a function keys(), which returns an iterable sequence of dictionary keys. Using for loop we can iterate over the sequence of keys returned by the function keys() and while iteration we can print each key. For example,
# Dictionary of string and int word_freq = { 'Hello': 56, "at": 23, 'test': 43, 'This': 78, 'Why': 11 } # Iterate over all keys of a dictionary # and print them one by one for key in word_freq.keys(): print(key)
Output:
Hello at test This Why
We can also create a list of keys from the iterable sequence returned by dict.keys() function. Then we print all the items of the list (all keys of the dictionary). For example,
# Dictionary of string and int word_freq = { 'Hello': 56, "at": 23, 'test': 43, 'This': 78, 'Why': 11 } # Get all keys of a dictionary as list list_of_keys = list(word_freq.keys()) # Print the list containing all keys of dictionary print(list_of_keys)
We can also use this list comprehension to iterate over all the keys of dictionary and then print each key one by one. For example,
# Dictionary of string and int word_freq = { 'Hello': 56, "at": 23, 'test': 43, 'This': 78, 'Why': 11 } # Iterate over all keys of dictionary # and print them one by one [print(key) for key in word_freq]
We have created a function, which yields all keys of the given dictionary. For each key-value pair in dictionary, it checks if the value is of dictionary type or not. If value is of dictionary type, then this function calls itself to access all keys of the nested dictionary and yield them too, one by one. The process goes on and on till all the nested dictionaries are covered. For example,
# A Nested dictionary i.e.dictionaty of dictionaries students = { 'ID 1': { 'Name': 'Shaun', 'Age': 35, 'City': 'Delhi' }, 'ID 2': { 'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai' }, 'ID 3': { 'Name': 'Smriti', 'Age': 33, 'City': 'Sydney' }, 'ID 4': { 'Name': 'Jacob', 'Age': 23, 'City': { 'perm': 'Tokyo', 'current': 'London' } }, } def all_keys(dict_obj): '' ' This function generates all keys of a nested dictionary. '' ' # Iterate over all keys of the dictionary for key, value in dict_obj.items(): yield key # If value is of dictionary type then yield all keys # in that nested dictionary if isinstance(value, dict): for k in all_keys(value): yield k # Iterate over all keys of a nested dictionary # and print them one by one. for key in all_keys(students): print(key)
Then, a follow up question (of course): Is it possible to modify the function so it returns keys (for example) while maintaining their hierarchy/order?,Sometime the position of an element in the tree is important; that's why I'm asking.
def get_keys(dictionary):
result = []
for key, value in dictionary.items():
if type(value) is dict:
new_keys = get_keys(value)
result.append(key)
for innerkey in new_keys:
result.append(f '{key}/{innerkey}')
else:
result.append(key)
return result
In the above program, we create an empty dictionary 3 inside the dictionary people.,In the above program, we delete the key:value pairs of married from internal dictionary 3 and 4. Then, we print the people[3] and people[4] to confirm changes.,Then, we add the key:value pair i.e people[3]['Name'] = 'Luna' inside the dictionary 3. Similarly, we do this for key age, sex and married one by one. When we print the people[3], we get key:value pairs of dictionary 3.,In the above program, we assign a dictionary literal to people[4]. The literal have keys name, age and sex with respective values. Then we print the people[4], to see that the dictionary 4 is added in nested dictionary people.
In Python, a dictionary is an unordered collection of items. For example:
dictionary = {
'key': 'value',
'key_2': 'value_2'
}
In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.
nested_dict = {
'dictA': {
'key_1': 'value_1'
},
'dictB': {
'key_2': 'value_2'
}
}
Example 1: How to create a nested dictionary
people = {
1: {
'name': 'John',
'age': '27',
'sex': 'Male'
},
2: {
'name': 'Marie',
'age': '22',
'sex': 'Female'
}
}
print(people)
Example 2: Access the elements using the [] syntax
people = {
1: {
'name': 'John',
'age': '27',
'sex': 'Male'
},
2: {
'name': 'Marie',
'age': '22',
'sex': 'Female'
}
}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
Example 3: How to change or add elements in a nested dictionary?
people = {
1: {
'name': 'John',
'age': '27',
'sex': 'Male'
},
2: {
'name': 'Marie',
'age': '22',
'sex': 'Female'
}
}
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'
print(people[3])
To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor.,There are several ways to create a nested dictionary using a type constructor called dict().,Adding or updating nested dictionary items is easy. Just refer to the item by its key and assign a value. If the key is already present in the dictionary, its value is replaced by the new one.,A nested dictionary is created the same way a normal dictionary is created. The only difference is that each value is another dictionary.
D = {
'emp1': {
'name': 'Bob',
'job': 'Mgr'
},
'emp2': {
'name': 'Kim',
'job': 'Dev'
},
'emp3': {
'name': 'Sam',
'job': 'Dev'
}
}
D = dict(emp1 = { 'name': 'Bob', 'job': 'Mgr' }, emp2 = { 'name': 'Kim', 'job': 'Dev' }, emp3 = { 'name': 'Sam', 'job': 'Dev' }) print(D) # Prints { 'emp1': { 'name': 'Bob', 'job': 'Mgr' }, # 'emp2': { 'name': 'Kim', 'job': 'Dev' }, # 'emp3': { 'name': 'Sam', 'job': 'Dev' } }
IDs = ['emp1', 'emp2', 'emp3'] EmpInfo = [{ 'name': 'Bob', 'job': 'Mgr' }, { 'name': 'Kim', 'job': 'Dev' }, { 'name': 'Sam', 'job': 'Dev' } ] D = dict(zip(IDs, EmpInfo)) print(D) # Prints { 'emp1': { 'name': 'Bob', 'job': 'Mgr' }, # 'emp2': { 'name': 'Kim', 'job': 'Dev' }, # 'emp3': { 'name': 'Sam', 'job': 'Dev' } }
IDs = ['emp1', 'emp2', 'emp3'] Defaults = { 'name': '', 'job': '' } D = dict.fromkeys(IDs, Defaults) print(D) # Prints { 'emp1': { 'name': '', 'job': '' }, # 'emp2': { 'name': '', 'job': '' }, # 'emp3': { 'name': '', 'job': '' } }
D = { 'emp1': { 'name': 'Bob', 'job': 'Mgr' }, 'emp2': { 'name': 'Kim', 'job': 'Dev' }, 'emp3': { 'name': 'Sam', 'job': 'Dev' } } print(D['emp1']['name']) # Prints Bob print(D['emp2']['job']) # Prints Dev
print(D['emp1']['salary'])
# Triggers KeyError: 'salary'
Keys: keep track of the current anycodings_nested recursion path. Yield the current path anycodings_nested as soon as you hit a leaf.,This is the input dictionary that was read anycodings_python by the python code:-,I have some dictionaries(json output). I anycodings_python want to get the base element which can be a anycodings_python list of strings or a string. Currently I am anycodings_python doing it like this:-,How to find census tract from latitude and longitude in python
I have some dictionaries(json output). I anycodings_python want to get the base element which can be a anycodings_python list of strings or a string. Currently I am anycodings_python doing it like this:-
folder = "shared/"
files = os.listdir('shared')
for f in files:
f = folder + f
print(f)
with open(f) as f:
data = json.load(f)
#data is a dict now with sub - keys
for key, value in data.items():
if value.keys():
print(value)
break
This is the input dictionary that was read anycodings_python by the python code:-
{
"shortshirt": {
"ralphlauren": {
"classic": [
"That Ralph Lauren classic fit is a timeless look!",
"Nice choice. Can’t go wrong with Ralph Lauren"
]
}
},
"socks": {
"": {
"": ["Have to find the right socks to keep your feet cozy"]
}
}
}
And this is the output that I am getting:-
{
'ralphlauren': {
'classic': ['That Ralph Lauren classic fit is a timeless look!', 'Nice choice. Can’t go wrong with Ralph Lauren']
}
} {
'': {
'': ['Have to find the right socks to keep your feet cozy']
}
}
Code:
def getitems(obj): def getkeys(obj, stack): for k, v in obj.items(): k2 = ([k] if k else []) + stack # don 't return empty keys if v and isinstance(v, dict): for c in getkeys(v, k2): yield c else: # leaf yield k2 def getvalues(obj): for v in obj.values(): if not v: continue if isinstance(v, dict): for c in getvalues(v): yield c else: # leaf yield v if isinstance(v, list) else [v] return list(getkeys(obj, [])), list(getvalues(obj))
Input:
{
"shortshirt": {
"ralphlauren": {
"classic": [
"That Ralph Lauren classic fit is a timeless look!",
"Nice choice. Can't go wrong with Ralph Lauren"
]
}
},
"socks": {
"": {
"": ["Have to find the right socks to keep your feet cozy"]
}
}
}
Output:
# keys
[['classic', 'ralphlauren', 'shortshirt'], ['socks']]
# values
[['That Ralph Lauren classic fit is a timeless look!', "Nice choice. Can't go wrong with Ralph Lauren"], ['Have to find the right socks to keep your feet cozy']]