Python-like dictionaries for Go

Overview

Dict

GoDoc Go Report Card Coverage Status Build Status

Python dictionary data type (dict) in Go

Package dict is a Go implementation of Python dict, which are hashable object maps. Dictionaries complement Go map and slice types to provide a simple interface to store and access key-value data with relatively fast performance at the cost of extra memory. This is done by using the features of both maps and slices.

Quick Start

Install using "go get":

go get github.com/srfrog/dict

Then import from your source:

import "github.com/srfrog/dict"

View example_test.go for an extended example of basic usage and features.

Features

  • Initialize a new dict with scalars, slices, maps, channels and other dictionaries.
  • Go types int, uint, float, string and fmt.Stringer are hashable for dict keys.
  • Go map keys are used for dict keys if they are hashable.
  • Dict items are sorted in their insertion order, unlike Go maps.
  • Go routine safe with minimal mutex locking (WIP)
  • Builtin JSON support for marshalling and unmarshalling
  • sql.Scanner support via optional sub-package (WIP)
  • Plenty of tests and examples to get you started quickly (WIP)

Documentation

The full code documentation is located at GoDoc:

http://godoc.org/github.com/srfrog/dict

The source code is thoroughly commented, have a look.

Usage

Minimal example showing basic usage:

package main

import (
	"fmt"

	"github.com/srfrog/dict"
)

type Car struct {
	Model, BrandID string
	Recalls        int
}

func main() {
	// Map of car models, indexed by VIN.
	// Data source: NHTSA.gov
	vins := map[string]*Car{
		"2C3KA43R08H129584": &Car{
			Model:   "2008 CHRYSLER 300",
			BrandID: "ACB9976A-DB5F-4D57-B9A8-9F5C53D87C7C",
			Recalls: 1,
		},
		"1N6AD07U78C416152": &Car{
			Model:   "2008 NISSAN FRONTIER SE-V6 RWD",
			BrandID: "003096EE-C8FC-4C2F-ADEF-406F86C1F70B",
			Recalls: 5,
		},
		"WDDGF8AB8EA940372": &Car{
			Model:   "2014 Mercedes-Benz C300W4",
			BrandID: "57B7B707-4357-4306-9FD6-1EDCA43CF77B",
			Recalls: 4,
		},
	}

	// Create new dict and initialize with vins map.
	d := dict.New(vins)

	// Add a couple more VINs.
	d.Set("1N4AL2AP4BN404580", &Car{
		Model:   "2011 NISSAN ALTIMA 2.5 S CVT",
		BrandID: "003096EE-C8FC-4C2F-ADEF-406F86C1F70B",
		Recalls: 2,
	})
	d.Set("4T1BE46K48U762452", &Car{
		Model:   "2008 TOYOTA Camry",
		BrandID: "C5764FE4-F1E8-46BE-AFC6-A2FC90110387",
		Recalls: 5,
	})

	// Check current total
	fmt.Println("Total VIN Count:", d.Len())

	// Print VINs that have 3 or more recalls
	for item := range d.Items() {
		car, ok := item.Value.(*Car)
		if !ok {
			continue // Not a Car
		}
		if car.Recalls < 3 {
			continue // Not enough recalls
		}
		fmt.Println("---")
		fmt.Println("VIN:", item.Key)
	}
}
You might also like...
I like reading news but I also like the terminal. I am leaning and practicing my go.
I like reading news but I also like the terminal. I am leaning and practicing my go.

I made an api and didn't know how to use it. Screenshots The initial screen when you first run the app. The screen after you specify an id. This app u

Building powerful interactive prompts in Go, inspired by python-prompt-toolkit.
Building powerful interactive prompts in Go, inspired by python-prompt-toolkit.

go-prompt A library for building powerful interactive prompts inspired by python-prompt-toolkit, making it easier to build cross-platform command line

Port of webcolors library from Python to Go

go-webcolors A library for working with color names and color value formats defined by the HTML and CSS specifications for use in documents on the Web

:key: Idiotproof golang password validation library inspired by Python's passlib

passlib for go Python's passlib is quite an amazing library. I'm not sure there's a password library in existence with more thought put into it, or wi

Create isolated environments for installing Go packages. Similar to virtualenv for Python.

DEPRECATED: This project is no longer maintained. Goenv Goenv lets you create an isolated environment where you install Go packages, binaries, or even

Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs.

go-attr Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs. This package provides user frien

Building powerful interactive prompts in Go, inspired by python-prompt-toolkit.
Building powerful interactive prompts in Go, inspired by python-prompt-toolkit.

go-prompt A library for building powerful interactive prompts inspired by python-prompt-toolkit, making it easier to build cross-platform command line

GoRose(go orm), a mini database ORM for golang, which inspired by the famous php framwork laravle's eloquent. It will be friendly for php developer and python or ruby developer. Currently provides six major database drivers: mysql,sqlite3,postgres,oracle,mssql, Clickhouse.
Python's repr() for Go

Python's repr() for Go This package attempts to represent Go values in a form that can be used almost directly in Go source code. Unfortunately, some

gpython is a python interpreter written in go "batteries not included"

gpython gpython is a part re-implementation / part port of the Python 3.4 interpreter to the Go language, "batteries not included". It includes: runti

Grumpy is a Python to Go source code transcompiler and runtime.

Grumpy: Go running Python Overview Grumpy is a Python to Go source code transcompiler and runtime that is intended to be a near drop-in replacement fo

parody of some of the basic python core features (collections package)

collections import "github.com/marcsantiago/collections" Overview Index Subdirectories Overview Index func StringEncoder(encoder *bytes.Buffer, data D

a python command-line tool which draws basic graphs in the terminal
a python command-line tool which draws basic graphs in the terminal

Termgraph A command-line tool that draws basic graphs in the terminal, written in Python. Graph types supported: Bar Graphs Color charts Multi-variabl

Partial port of Python difflib package to Go

go-difflib THIS PACKAGE IS NO LONGER MAINTAINED. At this point, I have no longer the time nor the interest to work on go-difflib. I apologize for the

Teste prático para vaga de back-end Python / Go na Stone.

Stone_GitHub_API_Golang Teste prático para vaga de back-end Python / Go na Stone. Nota 1: Utilizar a branch Release Nota 2: É necessário adicionar o T

Python's webbrowser in Go. Simple API for opening web pages on your default browser.

webbrowser webbrowser provides a simple API for opening web pages on your default browser. It's inspired on Python's webbrowser package but lacks some

:key: Idiotproof golang password validation library inspired by Python's passlib

passlib for go 100% modules-free. Python's passlib is quite an amazing library. I'm not sure there's a password library in existence with more thought

⛳ A minimal programming language inspired by Ink, JavaScript, and Python.

⛳ Golfcart My blog post: Creating the Golfcart Programming Language Getting Started Scope Rules Usage Building and tests Contributions License Golfcar

Comments
  • Recalls was not implemented in example

    Recalls was not implemented in example

    The example was trying to filter based on number of recalls, but Recalls was not implemented or assigned. I added it real quick so the demo worked properly. The fmt package was also missing from imports, which mt IDE added automatically.)

    opened by instance-id 2
Owner
Mr. Gus
API developer, data engineer, machine learning alchemist, crypto pretender. Go, Rust, and Python are my friends.
Mr. Gus
Solutions to AlgoExpert Problems in Six Programming Languages: Python, Java, Go, C++, C#, JavaScript/TypeScript

Solutions to AlgoExpert Problems in Six Programming Languages: Python, Java, Go, C++, C#, JavaScript/TypeScript Discover solutions to AlgoExpert probl

Nsikak Imoh 11 Sep 19, 2022
A tree like tool help you to explore data structures in your redis server

Redis-view is a tree like tool help you explore data structures in your redis server

dreamersdw 19 Mar 17, 2022
Levenshtein distance and similarity metrics with customizable edit costs and Winkler-like bonus for common prefix.

A Go package for calculating the Levenshtein distance between two strings This package implements distance and similarity metrics for strings, based o

AGExt 69 Aug 18, 2022
An yet-another red-black tree implementation, with a C++ STL-like API.

A red-black tree with an API similar to C++ STL's. INSTALLATION go get github.com/yasushi-saito/rbtree EXAMPLE More examples can be fou

Yasushi Saito 18 Apr 25, 2022
publish a tree-like data structure from a backend to a front-end

tree-publish publish a tree-like data structure from a backend to a front-end. It needs to be a tree in order to publish the data as JSON document. If

Lutz Behnke 0 Dec 20, 2021
GoStruct2Table - format your struct like a table.

GoStruct2Table format your struct like a table. Installing $ go get -u -v github.com/runningzyp/GoStruct2Table Simple Example import parser "github.c

YunpengZhan 10 Aug 15, 2022
ZSet is an in-memory Redis like sorted set datastructure

zset Getting Started Installing To start using hash, install Go and run go get: $ go get -u github.com/arriqaaq/zset This will retrieve the library. U

Farhan 6 Aug 9, 2022
🏳️ Go package that provides function like assert of Python or C++.

gassert gassert is Go package that provides function like assert of Python or C++. With gassert, you can check validation of parameters or values more

KyuSik Kim 4 Aug 5, 2022
Generate random, pronounceable, sometimes even memorable, "superhero like" codenames - just like Docker does with container names.

Codename an RFC1178 implementation to generate pronounceable, sometimes even memorable, "superheroe like" codenames, consisting of a random combinatio

Luca Sepe 82 Sep 25, 2022
A plugin for argo which behaves like I'd like

argocd-lovely-plugin An ArgoCD plugin to perform various manipulations in a sensible order to ultimately output YAML for Argo CD to put into your clus

null 89 Sep 27, 2022