Tags down


flattened dictionary into nested dictionary of dictionaries of lists

By : user6112066
Date : July 30 2020, 05:00 PM
around this issue You can use the setdefault function to automatically build the nesting levels as you go through the data:
code :
data= [
    "player": "Kevin Durant",
    "team": "Thunder",
    "location": "Oklahoma City",
    "points": 15

    "player": "Jeremy Lin",
    "team": "Lakers",
    "location": "Los Angeles",
    "points": 22
    "player": "Kobe Bryant",
    "team": "Lakers",
    "location": "Los Angeles",
    "points": 51
    "player": "Blake Griffin",
    "team": "Clippers",
    "location": "Los Angeles",
    "points": 26

nested = dict()
for d in data:
    nested.setdefault(d["location"],dict()) \
          .setdefault(d["team"],    dict()) \
          .setdefault(d["player"],  list()) \

{  'Oklahoma City': 
           {  'Kevin Durant': [{'points': 15}] }
    'Los Angeles': 
              'Jeremy Lin': [{'points': 22}], 
              'Kobe Bryant': [{'points': 51}]
           {  'Blake Griffin': [{'points': 26}] }
def dictNesting(data,*levels):
    result = dict()
    for d in data:
        r = result
        for level in levels[:-1]:
            r = r.setdefault(d[level],dict())
        r = r.setdefault(d[levels[-1]],list())
        r.append({k:v for k,v in d.items() if k not in levels})
    return result
byLocation = dictNesting(data,"location","team")

{  'Oklahoma City':
       {  'Thunder': [
              {'player': 'Kevin Durant', 'points': 15}]
   'Los Angeles':
       {'Lakers': [
              {'player': 'Jeremy Lin', 'points': 22},
              {'player': 'Kobe Bryant', 'points': 51}],
        'Clippers': [
              {'player': 'Blake Griffin', 'points': 26}]
byPlayer = dictNesting(data,"player","location","team")

{  'Kevin Durant':
       {  'Oklahoma City':
              {  'Thunder': [{'points': 15}] }
   'Jeremy Lin':
       {  'Los Angeles':
              {'Lakers': [{'points': 22}]}
   'Kobe Bryant':
       {  'Los Angeles':
              {'Lakers': [{'points': 51}]}
   'Blake Griffin':
       {  'Los Angeles':
              {'Clippers': [{'points': 26}]}
def dictNesting(data,*levels,aggregate=False):
    result = dict()
    for d in data:
        r = result
        for level in levels[:-1]:
            r = r.setdefault(d[level],dict())
        r = r.setdefault(d[levels[-1]],[list,dict][aggregate]())
        content = ( (k,v) for k,v in d.items() if k not in levels)
        if aggregate:
            for k,v in content: r.setdefault(k,list()).append(v)
    return result
byCity = dictNesting(data,"location","team",aggregate=True)

{  'Oklahoma City':
             {'player': ['Kevin Durant'], 'points': [15]}},
   'Los Angeles':
             {'player': ['Jeremy Lin', 'Kobe Bryant'], 'points': [22, 51]},
             {'player': ['Blake Griffin'], 'points': [26]}

lakersPlayers = byCity["Los Angeles"]["Lakers"]["player"] 
# ['Jeremy Lin', 'Kobe Bryant']

lakersPoints  = sum(byCity["Los Angeles"]["Lakers"]["points"]) 
# 73

Share : facebook icon twitter icon

Creating a nested dictionary from a flattened dictionary

By : rkbalgi
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I have a flattened dictionary which I want to make into a nested one, of the form , Here is my take:
code :
def nest_dict(flat):
    result = {}
    for k, v in flat.items():
        _nest_dict_rec(k, v, result)
    return result

def _nest_dict_rec(k, v, out):
    k, *rest = k.split('_', 1)
    if rest:
        _nest_dict_rec(rest[0], v, out.setdefault(k, {}))
        out[k] = v

flat = {'X_a_one': 10,
        'X_a_two': 20, 
        'X_b_one': 10,
        'X_b_two': 20, 
        'Y_a_one': 10,
        'Y_a_two': 20,
        'Y_b_one': 10,
        'Y_b_two': 20}
nested = {'X': {'a': {'one': 10,
                      'two': 20}, 
                'b': {'one': 10,
                      'two': 20}}, 
          'Y': {'a': {'one': 10,
                      'two': 20},
                'b': {'one': 10,
                      'two': 20}}}
print(nest_dict(flat) == nested)
# True

Python: How to write a nested dictionary (dictionaries in lists in dictionaries) to a excel xlsx file

By : user3128299
Date : March 29 2020, 07:55 AM
hope this fix your issue For the .xlsx generation I would use XlsxWriter and Pandas dataframe. I assume you have this data in a variable named dictionary.
code :
import pandas as pd

# Get the "outer" dictionary keys
outer_dict_keys = dictinary.keys()
# Define the Pandas dataframe
df = pd.DataFrame(columns=dictinary["SHAMk98bspucm02.some-domain.invalid"]    [0].keys())       # It is quite ugly :D, just lack of time ... change it!

# Iterate through "outer" dictionary
for outer_dict_key in outer_dict_keys:
    # With this you get: SHAMk98bspucm02.some-domain.invalid, ...
    interior_dict = dictinary[outer_dict_key][0]        # The [0] is there     because it is in a list
    # Get the "interior" dictionary keys
    interior_dict_keys = interior_dict.keys()

    # This variable contains the data for one row.
    row = dict()
    for interior_dict_key in interior_dict_keys:
        # With this you get: Name, Device Class, Model ..
        row[interior_dict_key] = interior_dict[interior_dict_key]

    # You can reach the values like this:
    df = df.append(row, ignore_index=True)

# Create an xlsxwriter object and save the created Excel file
writer = pd.ExcelWriter('filename.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='sheet_name', index=False)

Creating a new dictionary from mapping of flattened nested dictionary

By : Vikash Tiwari
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You can loop over your dictionary items and check if the value is a dict again loop over its items and check if the key is in your specified keys then add the item to new dictionary :

Nested Dictionary from Lists and Other Dictionaries

By : W.rui
Date : March 29 2020, 07:55 AM
wish helps you names is ordered, but the keys of a dict are unordered, so you can't rely on zip(names,dict1) to correctly match names with keys (student ID). For example:

Speed performance difference between flattened dictionary and nested dictionary

By : SunEasy Vtm
Date : March 29 2020, 07:55 AM
it should still fix some issue
Looking at nested dictionaries structure, seems to me that a "hierarchical" approach may speed up the search of the keys. Am I wrong?
Related Posts Related Posts :
  • How can I assign varaibles to json response?
  • name 'df' is not defined in box plot
  • Comparing dataframe columns
  • Can I Override Global Authentication for a Single Request Type in an ApiView using DRF?
  • Celery chain performances
  • Why am I getting "asynchronous comprehension outside of an asynchronous function"?
  • Creating a file from a docker container
  • doing too many write operations in django rest framework and postgres
  • How to change the order of bar charts in Python?
  • Pandas Data Frame manipulation
  • an undefined error in a simple python code- KeyError: '284882215'
  • Pandas split column in several columns throug string replacement or regex
  • how value is passed from __init__ method in pyhton as it dose not return anyhting
  • Dynamically inherit all Python magic methods from an instance attribute
  • Asking user to input certain information
  • how to test a deep learning model in a new dataset
  • Is np.fft.fft working properly? I am getting very large frequency values
  • How can you delete similar characters at the same positions in 2 strings
  • Does insert (at the end of a list) have O(1) time complexity?
  • Automatically Creating List of Dictionaries Based Upon Two Lists of Equal Length with Python
  • Discrete Cosine Transform (DCT) Coefficient Distribution
  • multiprocessing.Pool not running on last element of iterable
  • Python: sorting string non lexicographically
  • Render images from media directory Django
  • Cannot understand why more vectorization is slower than less vectorization in this case?
  • Django - Use a property as a foreign key
  • creating a function that loops if you do not enter the correct variables
  • Confused on how to store 3D matrices in HDF5 file in matlab?
  • TOTP: Can someone use the same otp within 30s and misuse it
  • is it possible to have 2 type hints for 1 parameter in Python?
  • Can someone explain what this Numpy array property is called?
  • Better way to add the result of apply (multiple outputs) to an existing DataFrame with column names
  • Selecting choice numbers
  • Create variables from list PYTHON
  • This code takes forever to run but doesn't give an error
  • "return" and "return None" behavior difference in generator
  • AttributeError: 'str' object has no attribute 'fbind' error using kivy in Python
  • Python not importing files when not inside conda environment
  • Is it possible to override a class' __call__ method?
  • Python library for live coordinated plotting in map
  • Pandas: counting consecutive rows with condition
  • How to define that a return type of method is an implementation of superclass
  • How can I print to the Visual Studio Code console in Portuguese?
  • Google Appengine Standard Python 2.7: Can't run Google Endpoints on localhost dev_appserver.py anymore
  • google appengine Unauthorized status 401
  • Don't understand cause of this IndentationError in my tic tac toe script
  • How to read in key-value pair from a json file as a pandas dataframe?
  • Can decorator decorate a recursive function?
  • How do I create a nested for loop where I have control of the initial loop index value
  • Unexpected error when creating a SQLite database using python
  • Pythonic way to write cascading of loops and if statements?
  • Python Beginner - Having trouble with multiple choice quiz program
  • Itertools return value NOT used in combinations
  • Return a list of words that contain a letter
  • From rows to columns using Peewee ORM
  • Parse large text document, to keep only "account number", and a specific keyword ("Market Value")
  • Cannot append to my list without getting a nonetype object error
  • Python Train Test Split
  • Optimizing following Python List of Dictionary operation with better solution
  • In Pandas merge colum1 value with colum2, both col data type is object and only few values are null in first column?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org