Skip to main content

A handy library to manipulate dictionaries

Project description

Handy Dict

A library with some handy utils to deal with dictionaries that contain arrays

This file will become your README and also the index of your documentation.

Install

pip install handy-dict

How to use

Let's start with a dictionary

pikachu = {
  "name": "pikachu",
  "moves": [
    {
      "move": {
        "name": "mega-punch",
        "url": "https://pokeapi.co/api/v2/move/5/"
      }
    },
    {
      "move": {
        "name": "pay-day",
        "url": "https://pokeapi.co/api/v2/move/6/"
      }
    },
    {
      "move": {
        "name": "thunder-punch",
        "url": "https://pokeapi.co/api/v2/move/9/"
      }
    }
  ],
  "stats": [
    {
      "base_stat": 90,
      "effort": 2,
      "stat": {
        "name": "speed",
        "url": "https://pokeapi.co/api/v2/stat/6/"
      }
    },
    {
      "base_stat": 50,
      "effort": 0,
      "stat": {
        "name": "special-defense",
        "url": "https://pokeapi.co/api/v2/stat/5/"
      }
    }
  ]
}

apply_keyed

from handy_dict import apply_keyed

With handy-dict you can apply a function to the keys inside a dictionary, say you want to take name out of stat, go from something like this:

{
  "base_stat": 50,
  "effort": 0,
  "stat": {
    "name": "special-defense",
    "url": "https://pokeapi.co/api/v2/stat/5/"
  }
}

to this:

{
  "base_stat": 50,
  "name": "special-defense"
}

The function transform_stat is just a little helper that will transform the stats array in our pikachu dictionary and return a new array, that will replace the stats in a copy of the original dict:

def transform_stat(stat_array):
    return {
        stat["stat"]["name"]: stat["base_stat"] 
        for stat in stat_array 
    } 
modified_pikachu = apply_keyed(pikachu,["stats"], transform_stat)
modified_pikachu["stats"]
{'speed': 90, 'special-defense': 50}

return_keyed

from handy_dict import return_keyed

handy-dict also makes it easy to return multiple values from a dictionary, iterating through keys and arrays:

return_keyed(pikachu, ["moves","move","name"])
['mega-punch', 'pay-day', 'thunder-punch']

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

handy_dict-0.1.0.tar.gz (10.0 kB view hashes)

Uploaded Source

Built Distribution

handy_dict-0.1.0-py3-none-any.whl (9.8 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page