Search
 
SCRIPT & CODE EXAMPLE
 

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})})
Comment

python get nested dictionary keys

example_dict.get('key1', {}).get('key2')
Comment

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'}}
Comment

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'])
Comment

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'}]]
Comment

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
Comment

Nested dictionary Python

D = {'emp1': {'name': 'Bob', 'job': 'Mgr'},
     'emp2': {'name': 'Kim', 'job': 'Dev'},
     'emp3': {'name': 'Sam', 'job': 'Dev'}}
Comment

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)
Comment

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]
Comment

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
    },
]
Comment

python create nested dictionary

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

print(people)
Comment

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)
Comment

PREVIOUS NEXT
Code Example
Python :: Python NumPy Reshape function example 
Python :: how to create multiple columns after applying a function in pandas column python 
Python :: how to import packages in python 
Python :: create a virtual environment python 3 
Python :: python if in one line 
Python :: floor python 
Python :: Restrict CPU time or CPU Usage using python code 
Python :: get element by index in list python 
Python :: rstrip python3 
Python :: get row count dataframe pandas 
Python :: np.random.rand() 
Python :: django serializer method field read write 
Python :: 2--2 in python prints? 
Python :: opencv find image contained within an image 
Python :: python find in string 
Python :: Delete all small Latin letters a from the given string. 
Python :: what is a rare earth 
Python :: delete everything from list that matches string 
Python :: python glob sort numerically 
Python :: pythoon 
Python :: reverse every word from a sentence but maintain position 
Python :: init matrix in numpy 
Python :: print poo 
Python :: pyqt curves exemple 
Python :: django admin make column link 
Python :: how to code a discord bot in python nextcord 
Python :: yaml documentation 
Python :: numpy reg ex delete words before a specific character 
Python :: somebody please get rid of my annoying-as-hell sunburn!!! 
Python :: doc2text python example 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =