Skip to content

Commit

Permalink
Merge pull request #18 from ssghait007/examples
Browse files Browse the repository at this point in the history
Add examples
  • Loading branch information
Agent-Hellboy authored Oct 20, 2024
2 parents 51b85e4 + 0e8681d commit ed5b58b
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 11 deletions.
43 changes: 32 additions & 11 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Python library to trace path of a particular key inside a nested dict

.. image:: https://github.com/Agent-Hellboy/trace-dkey/actions/workflows/python-app.yml/badge.svg
:target: https://github.com/Agent-Hellboy/trace-dkey/

.. image:: https://img.shields.io/pypi/pyversions/trace-dkey.svg
:target: https://pypi.python.org/pypi/trace-dkey/

Expand All @@ -27,32 +27,33 @@ Python library to trace path of a particular key inside a nested dict
Installation
============

For stable version
For stable version
- pip install trace-dkey

For development
For development
- git clone https://github.com/Agent-Hellboy/trace-dkey
- cd trace-dkey
- python -m venv .venv
- cd trace-dkey
- python -m venv .venv
- source .venv/bin/activate

Documentation
=============

For more details, you can refer to the `documentation <https://agent-hellboy.github.io/trace-dkey/>`_.


General Info
============

- The value returned by the `trace` function is an array of paths, where each path is an array of dictionary keys.
- Because of that, the library can be used in a practical way by taking advantage of this format.
- In the example below we use the returned path to iterate over the dictionary keys and print the key value:

.. code:: py
from trace_dkey import trace
l={'a':{'b':{'c':{'d':{'e':{'f':1}}}}}}
paths = trace(l,'f')
for path in paths:
Expand All @@ -63,14 +64,34 @@ General Info
- This addresses a wide range of questions asked on StackOverflow about key inside a nested dict
- At least 13 duplicate questions can be found on Stackoverflow
- At least 13 duplicate questions can be found on Stackoverflow
- This can be tracked on https://you.com/search?q=find%20key%20in%20nested%20dictionary%20python


API Examples
============

Added example scripts demonstrating how to use trace-dkey with responses from popular APIs. These examples can be found in the `examples` folder:

1. GitHub API Example (`github_api_example.py`): Demonstrates fetching repository information
2. OpenWeatherMap API Example (`openweathermap_api_example.py`): Retrieves current weather data
3. JSONPlaceholder API Example (`jsonplaceholder_api_example.py`): Shows how to interact with a mock REST API

To run these examples:

1. Install the required dependencies:
``pip install -r examples/requirements.txt``

2. For the OpenWeatherMap example, you'll need to sign up for a free API key at https://openweathermap.org/ and set it as an environment variable:
``export OPENWEATHERMAP_API_KEY=your_api_key_here``

| Someone made a nice comparision of this lib(trace-dkey) with one of the famous lib(yamlpath) which is doing the similar thing
3. Run the examples:
``python examples/github_api_example.py``
``python examples/openweathermap_api_example.py``
``python examples/jsonplaceholder_api_example.py``

These examples demonstrate how to use trace-dkey to find specific keys in nested JSON responses from real-world APIs.

| Someone made a nice comparison of this lib(trace-dkey) with one of the famous lib(yamlpath) which is doing the similar thing
.. image:: /images/img.png
:width: 600
Expand Down
27 changes: 27 additions & 0 deletions examples/github_api_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import requests
from trace_dkey import trace

# GitHub API example
def github_api_example():
# Get information about a GitHub repository
repo = "Agent-Hellboy/trace-dkey"
url = f"https://api.github.com/repos/{repo}"
response = requests.get(url)
data = response.json()

# Find the path to the 'stargazers_count' key
paths = trace(data, 'stargazers_count')
print("Paths to 'stargazers_count':")
for path in paths:
print(" -> ".join(path))
print(f"Value: {data['stargazers_count']}")

# Find the path to the 'login' key (owner's login)
paths = trace(data, 'login')
print("\nPaths to 'login':")
for path in paths:
print(" -> ".join(path))
print(f"Value: {data['owner']['login']}")

if __name__ == "__main__":
github_api_example()
31 changes: 31 additions & 0 deletions examples/jsonplaceholder_api_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import requests
from trace_dkey import trace

# JSONPlaceholder API example
def jsonplaceholder_api_example():
# Get a sample post
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
post_data = response.json()

# Find the path to the 'title' key
paths = trace(post_data, 'title')
print("Paths to 'title':")
for path in paths:
print(" -> ".join(path))
print(f"Value: {post_data['title']}")

# Get comments for the post
url = "https://jsonplaceholder.typicode.com/posts/1/comments"
response = requests.get(url)
comments_data = response.json()

# Find the path to the 'email' key in the first comment
paths = trace(comments_data[0], 'email')
print("\nPaths to 'email' in the first comment:")
for path in paths:
print(" -> ".join(path))
print(f"Value: {comments_data[0]['email']}")

if __name__ == "__main__":
jsonplaceholder_api_example()
29 changes: 29 additions & 0 deletions examples/openweathermap_api_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import requests
import os
from trace_dkey import trace

# OpenWeatherMap API example
def openweathermap_api_example():
# You need to sign up for a free API key at https://openweathermap.org/
api_key = os.environ.get('OPENWEATHERMAP_API_KEY', 'your_api_key_here')
city = "London"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(url)
data = response.json()

# Find the path to the 'temp' key (current temperature)
paths = trace(data, 'temp')
print("Paths to 'temp':")
for path in paths:
print(" -> ".join(path))
print(f"Value: {data['main']['temp']} K")

# Find the path to the 'description' key (weather description)
paths = trace(data, 'description')
print("\nPaths to 'description':")
for path in paths:
print(" -> ".join(path))
print(f"Value: {data['weather'][0]['description']}")

if __name__ == "__main__":
openweathermap_api_example()
2 changes: 2 additions & 0 deletions examples/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
requests==2.26.0
trace-dkey==0.0.4

0 comments on commit ed5b58b

Please sign in to comment.