logo
Tags down

shadow

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()) \
          .append({"points":d["points"]})
print(nested)

{  'Oklahoma City': 
    {  
       'Thunder': 
           {  'Kevin Durant': [{'points': 15}] }
    }, 
    'Los Angeles': 
    { 
       'Lakers': 
           {  
              'Jeremy Lin': [{'points': 22}], 
              'Kobe Bryant': [{'points': 51}]
           }, 
       'Clippers': 
           {  '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)
        else:
            r.append(dict(content))
    return result
byCity = dictNesting(data,"location","team",aggregate=True)

{  'Oklahoma City':
        {'Thunder':
             {'player': ['Kevin Durant'], 'points': [15]}},
   'Los Angeles':
        {'Lakers':
             {'player': ['Jeremy Lin', 'Kobe Bryant'], 'points': [22, 51]},
         'Clippers':
             {'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, {}))
    else:
        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)
writer.save()
writer.close()

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 :
  • Adding quotations around words preceding a colon in Python
  • Write a class that draws an image in the center of the screen in PyGame
  • Python requirements conflict with PyPi
  • A good way to make classes for more complex playing card types than those found in a standard deck?
  • How to find the longest chain of consecutively recurring character groupings in file
  • Class variable that is an instance of itself
  • SQLAlchemy(Python)/Sequelize(Node.js) rollback transation (undo button)
  • Word2Vec compare vectors from different models with different sizes
  • Pandas: Create a table with a “dummy variable” of another table
  • How to implement Python's multiprocessing Pool to convert thousands of files
  • Remove elements from lists, code is leaving just one
  • Ensure python script isn't run as root
  • How do I sum 2 specific column rows in a DataFrame if some of the values are NaN?
  • Mocking __init__ of a class imported in file
  • How to check a greater than check in reg expression?
  • How to make the progressbar work, It freezes the window
  • How to update the state of a Toggle Button after process completion?
  • How to specify the outer product of certain axis in python?
  • multiprocessing creates zombie process even after .join()
  • Why does the robot framework add quotation marks to a command string?
  • How to extract the orderconfirmedoid from from the current url using Selenium and Python
  • How to find a sum of even numbers in range recursively?
  • How to convert list of pixel into image using python
  • How can I bind the enter key to a command while having a button do the same thing?
  • python: subsetting and renaming columns by name in list of dataframes
  • print x over y in matplotlib python
  • Python Image Processing on Captcha how to remove noise
  • Pass value to string imported from another module using f-string
  • Greatest of 3 numbers code not working for specific numbers
  • Use of function inside a for loop
  • Cant match a particular pattern in regex using OR
  • when i build the docker with pip install psycopg2 has error
  • 'import ase' does not load submodule 'ase.io'
  • I have two tuple comparison. Almost the same data. Why this error:
  • Why hasn't this list changed?
  • Scrape html data using beautifulsoup and Python
  • JupyterLab - python open() function results in FileNotFoundError
  • I'm not getting proper output for checking a string to be palindrome or not
  • alphabet split instead of word split using lists
  • Celsius to Fahrenheit method doesn't work
  • How to import a module at each execution of python?
  • find contours of thresholded image
  • How to use sleep to limit data put in logs?
  • Dataframe expanding window and applying multiple functions
  • How to get integer list from a string but not integer list?
  • Rename dataframe in Python for loop
  • Unable to fetch rows from PostGresSQL table
  • How to pass values to a function which is a list item in Python
  • Easiest way to subclass a widget in Python for use with Qt Designer
  • Finding the cumulative sum of a list
  • Pandas Dataframe Update Rows
  • How to solve this loop problem in python flask?
  • Python Opencv: Filter Image for Text Detection
  • Python - Count Numbers of Different Digits in String
  • How to update, rotate and display a ply file with python?
  • Grouping by and filtering for column value containing string and aggregate function?
  • pandas group by day or week or month for timestamp
  • Django converting year to a full date
  • Clunky/slow dragging functionality on my analog clock project
  • Setting the labels of colorbar matplotlib
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org