DekGenius.com
PYTHON
python counter nested dictionary
import collections
a = collections.defaultdict(collections.Counter)
inf = [('fruit','apple'),('car','truck'),('fruit','banana'),('fruit','banana')]
for category,item in inf:
a[category][item] = a[category][item] + 1
#print(a)
#{'fruit': Counter({'banana': 2, 'apple': 1}), 'car': Counter({'truck': 1})})
python get nested dictionary keys
example_dict.get('key1', {}).get('key2')
Nested dictionary Python
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'}}
Accessing elements from a Python Nested Dictionary
# welcome to softhunt.net
# Creating a Dictionary
Dictionary = {0: 'Softhunt', 1: '.net',
2:{'i' : 'By', 'ii' : 'Ranjeet', 'iii' : 'Andani'}}
print('Dictionary', Dictionary)
# Accessing element using key
print(Dictionary[0])
print(Dictionary[2]['i'])
print(Dictionary[2]['ii'])
create dictionary from a nested list
my_dict= 'mc': [[{'id': '1.185662381',
'marketDefinition': {'bspMarket': False,
'turnInPlayEnabled': True,
'persistenceEnabled': True,
'marketBaseRate': 5.0,
'eventId': '30729399',
'eventTypeId': '1',
'numberOfWinners': 1,
'bettingType': 'ODDS'}],
[{'id': '1.185662380',
'marketDefinition': {'bspMarket': True,
'turnInPlayEnabled': False,
'persistenceEnabled': True,
'marketBaseRate': 5.0,
'eventId': '30729399',
'eventTypeId': '1',
'numberOfWinners': 1,
'bettingType': 'ODDS'}]]
python nested object to dict
def my_dict(obj):
if not hasattr(obj,"__dict__"):
return obj
result = {}
for key, val in obj.__dict__.items():
if key.startswith("_"):
continue
element = []
if isinstance(val, list):
for item in val:
element.append(my_dict(item))
else:
element = my_dict(val)
result[key] = element
return result
Nested dictionary Python
D = {'emp1': {'name': 'Bob', 'job': 'Mgr'},
'emp2': {'name': 'Kim', 'job': 'Dev'},
'emp3': {'name': 'Sam', 'job': 'Dev'}}
Creating a Nested Dictionary
# welcome to softhunt.net
# Creating a Nested Dictionary
Dictionary = {0: 'Softhunt', 1: '.net',
2:{'i' : 'By', 'ii' : 'Ranjeet', 'iii' : 'Andani'}}
print(Dictionary)
nested dict
def dict_generator(indict, pre=None):
pre = pre[:] if pre else []
if isinstance(indict, dict):
for key, value in indict.items():
if isinstance(value, dict):
for d in dict_generator(value, pre + [key]):
yield d
elif isinstance(value, list) or isinstance(value, tuple):
for v in value:
for d in dict_generator(v, pre + [key]):
yield d
else:
yield pre + [key, value]
else:
yield pre + [indict]
nesting a dictionary in a list python
#Nesting a Dictionary Inside a list
travel_log = [
{
"country": "France",
"cities_visited" : ["Paris", "Lille", "Dijon"],
"total_visits" : 12
},
{"country": "Germany" ,
"cities_visited" :["Berlin", "Hamburg", "Stuttgart"],
"total_visits" : 12
},
]
python create nested dictionary
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people)
make nested dict from two dict
data = [
[14, 77766, [2, 2]],
[15, 77766, [1, 2]],
[70, 88866, [1, 5]],
[71, 88866, [2, 5]],
[72, 88866, [5, 5]],
[73, 88866, [4, 5]],
[74, 88866, [3, 5]],
[79, 99966, [1, 2]],
[80, 99966, [2, 2]],
]
c = {}
for key, id_, (value, _) in data:
c.setdefault(id_, {})[key] = value
print(c)
© 2022 Copyright:
DekGenius.com