# Key-Value Pairs: Definition, Examples & How They Work

> This guide explains the structure, shows examples in code and JSON, and examines where key-value storage fits alongside relational data and AI agents investigating business problems.

- Canonical URL: https://www.puppygraph.com/blog/key-value-pairs
- Published: 2026-12-04
- Author: Hao Wu

Key-value pairs make data easy to retrieve when you know its name or identifier. An application can look up an order's status, read a configuration setting, or recover a user's session through the same basic pattern. For an AI agent investigating delivery delays, the harder question is deciding which records to retrieve when the task extends beyond a known identifier.

This guide explains the structure, shows examples in code and JSON, and examines where key-value storage fits alongside relational data and AI agents investigating business problems.

## What are key-value pairs?

A key-value pair associates an identifying key with a value. The key provides the lookup handle; the value holds the associated information. In `"status": "delayed"`, `status` is the key and `delayed` is the value.

The value can be a scalar, such as a string or number, or a collection containing more data. Supported types depend on the language, format, or database.

Within a conventional map or dictionary, each key identifies one value. Different keys can hold identical values, and the same key can appear in separate dictionaries. Two order records can each contain a `status` field without conflicting.

A key-value pair is a representation, not a database category by itself. You can use pairs in application memory, configuration files, API messages, or a persistent key-value store. Those environments have different rules for durability, ordering, and access.

## How key-value pairs work

The basic operations are to associate a value with a key, retrieve it, replace it, and delete the association. A Python dictionary demonstrates all four:

```python
order = {}
order["status"] = "processing"
print(order["status"])                # processing
order["status"] = "delayed"
print(order["status"])                # delayed
del order["status"]
print(order.get("status", "unknown")) # unknown
```

Assigning an existing key replaces its value. Reading a missing key with square brackets raises `KeyError`; `get()` can return a chosen default instead. These are [Python dictionary rules](https://docs.python.org/3/tutorial/datastructures.html#dictionaries), not universal behavior for every storage system.

The lookup mechanism is a separate implementation choice. [CPython uses hash tables](https://docs.python.org/3/faq/design.html#how-are-dictionaries-implemented-in-cpython): a hash derived from the key helps locate the entry, normally without checking every stored pair. A hash collision does not make two different keys identical; the implementation distinguishes them through key comparison.

Key-value notation alone promises no particular latency. A remote database lookup also involves network access, storage, and possibly replication. Likewise, replacing one value does not automatically make a sequence of operations transactional.

## Key-value pair examples

The same structure appears at different levels:

| **Context** | **Key** | **Value** | **Purpose** |
| --- | --- | --- | --- |
| Configuration | `retry_limit` | `3` | Set an application's retry count |
| User preferences | `theme` | `"dark"` | Select a display preference |
| Order cache | `order:O-1042` | An order record | Retrieve one order by identifier |
| Field inside that record | `shipment_id` | `"S-882"` | Identify its shipment |

Notice the two levels in the order example. The outer key, `order:O-1042`, identifies a whole record. Inside its value, field names identify individual attributes. The colon in the outer key is an application naming convention; it does not automatically create a relationship with another record.

![One outer key retrieves a record; field keys identify the attributes inside its value.](https://o6xswp5m6ilbks2z.public.blob.vercel-storage.com/uploads/ab8e18ef4ebebeddc0b3152c/5f451199-4ca3-4c39-8f31-760ef9aa94c6/key-value-pairs-figure-1-d473ad822d.png)

Figure: One outer key retrieves a record; field keys identify the attributes inside its value.

## Key-value pairs in JSON

JSON objects represent collections of name-value pairs. An order API might return:

```json
{
  "order_id": "O-1042",
  "status": "delayed",
  "shipment_id": "S-882",
  "delivery_attempts": 2,
  "notifications_enabled": true,
  "delivery": {
    "region": "north",
    "instructions": null
  }
}
```

Object names must be strings enclosed in double quotes. Values can be strings, numbers, booleans, `null`, arrays, or nested objects. Here, `delivery` holds another object, while `delivery_attempts` holds a number.

The [JSON specification, RFC 8259](https://datatracker.ietf.org/doc/html/rfc8259#section-4), recommends unique names within an object. Duplicate names can produce different results across parsers, so avoid them. Object-member order should not carry business meaning; use an array when sequence matters.

JSON defines a data interchange format. It does not determine how a server indexes, stores, or queries the represented records. Returning this object from an API says nothing about whether the backend uses a key-value database, relational tables, or another storage model.

## Key-value pairs in databases

A key-value database makes lookup by key a central access pattern. For example, these Redis commands store and retrieve an order status:

```
SET order:O-1042:status delayed EX 300
GET order:O-1042:status
```

Redis [`SET`](https://redis.io/docs/latest/commands/set/) writes the string and, with `EX 300`, sets a five-minute expiration. [`GET`](https://redis.io/docs/latest/commands/get/) retrieves it while the key exists. Expiration is useful for a cache, but a cache miss must be handled by the application, often by reading the authoritative record.

Key-value databases differ in how much structure they understand. [DynamoDB identifies items](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html) through either a partition key or a composite partition-and-sort key. It also supports secondary indexes for other access patterns. This is more capable than treating every value as opaque bytes.

Choose the key around the reads the application needs. Retrieving `O-1042` is a different operation from finding every delayed order in the north region. The latter needs suitable indexing, a scan, or another query path.

## Key-value pairs vs relational data

Relational tables can also store keys and values. The useful comparison is between a database organized around key-based access and a relational model that exposes named columns, relationships, and set-based queries.

| **Dimension** | **Key-value storage model** | **Relational data model** |
| --- | --- | --- |
| Typical read | Retrieve a value using its key | Select rows using predicates and combine tables |
| Record shape | Values may vary, subject to store rules | Columns and constraints define the table structure |
| Relationships | Encoded in keys, values, or application-maintained structures | Represented through matching columns and queried with joins |
| Integrity | Depends on the store and application | Can use primary keys, foreign keys, and other constraints |
| Update trade-off | Duplicated values may need coordinated updates | Normalized facts reduce duplication but can require joins when reading |

For the order example, relational tables might separate `orders`, `shipments`, and `carriers`. A [join combines related rows](https://www.postgresql.org/docs/current/tutorial-join.html), while a [foreign-key constraint](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-FK) can ensure that a referenced shipment exists. A field named `shipment_id` inside an arbitrary value does not provide that guarantee by itself.

An agent investigating delivery delays needs both retrieval and discovery. It may start with an order, then examine shipment events and shared sorting hubs. As evidence spreads across more tables and longer histories, the agent needs a usable model of those connections, not just identifiers for records it already knows.

## Benefits of key-value pairs

**Direct access.** A known key gives an application a straightforward way to retrieve its associated value. This fits repeated operations such as checking one order or reading one user's preferences.

**Flexible values.** A mapping can hold a simple setting or a structured record. Applications can represent optional attributes without requiring every value to have the same shape, where the chosen store permits it. They still need validation and conventions for interpreting those fields.

**Distribution by key.** Distributed stores can use keys to assign records to partitions and spread work across machines. The design must spread requests as well as data: [DynamoDB's partition-key guidance](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html) emphasizes distributing activity across keys. One heavily accessed key can remain a bottleneck even when the overall dataset is well distributed.

These benefits come from matching storage to access patterns. A concise representation alone does not ensure efficient searches over arbitrary values.

## Common use cases for key-value pairs

**Configuration and preferences.** Applications associate names with settings such as retry limits, language, and notification choices. Validation establishes which keys and values are accepted.

**Sessions and caches.** A session identifier can locate application state; an order identifier can locate a cached status. Expiration and refresh rules determine how long those records remain useful.

**APIs and application messages.** Named fields let a receiver distinguish identifiers, statuses, and counts. A JSON response can carry these fields independently of the storage model behind the API.

**Agent task state.** An investigation can record its current hypothesis, examined identifiers, and next action as key-value fields. For delivery delays, an agent might test warehouse processing time, then investigate carrier routes if warehouse timing looks normal. The agent uses each result to choose its next query.

That investigation needs quick successive reads and access to evidence across growing operational datasets. If shipment histories already live in warehouse or lakehouse tables, reusing those tables avoids maintaining another investigation-specific dataset. The agent's task state and its evidence-access layer serve different purposes.

## Limitations of key-value pairs

**Searching by value needs support.** A direct key lookup does not automatically answer filters, rankings, or aggregations over many records. Those operations need indexes, scans, or additional query capabilities.

**Duplication creates coordination work.** Copying a carrier's details into every order can simplify reads, but changes must reach every relevant copy. Concurrent updates also need an explicit consistency strategy.

**Identifiers do not explain relationships.** An order's `shipment_id` points toward another record, but it does not describe the shipment's route or which other orders share its hubs. An agent must discover and test those connections to investigate a common delay.

For that investigation, [PuppyGraph](https://www.puppygraph.com/) helps an agent follow orders through shipments and shared delivery dependencies in existing enterprise tables. It is a data engine for building AI agents across 3,000 tables, with a distributed execution engine that scales to petabytes and supports [subsecond relationship queries](https://www.puppygraph.com/benchmarks) on supported workloads, helping agents test successive hypotheses. It [queries supported SQL databases, warehouses, and lakehouses in place](https://www.puppygraph.com/how-it-works), including direct reads of Iceberg and Delta Lake, with no data movement into a separate graph database; the same tables remain available to SQL.

![PuppyGraph queries the existing tables in place, so graph and SQL queries share one copy of the data and no pipeline keeps a graph copy in sync.](https://o6xswp5m6ilbks2z.public.blob.vercel-storage.com/uploads/ab8e18ef4ebebeddc0b3152c/ef1496f9-cf08-4b8b-933c-8baac5450baa/snowflake-zero-copy-clone-figure-2-0777fe67cc.png)

Figure: PuppyGraph queries the existing tables in place, so graph and SQL queries share one copy of the data and no pipeline keeps a graph copy in sync.

The built-in AI assistant proposes a graph model of entities and relationships from connected tables for review. Agents can access that model through [MCP](https://docs.puppygraph.com/ai/ai-integrations/#tools), using openCypher or Gremlin to retrieve evidence. With [strict schema validation](https://docs.puppygraph.com/querying/querying-using-opencypher/#strict-schema-validation) enabled, openCypher queries referencing undefined entities or relationships are rejected with feedback the agent can use to correct them.

In the delivery scenario, an agent could follow a suspected hub, compare affected shipments with routes that bypass it, and revise its hypothesis from the results. A shared hub is a lead to test, not proof of the cause. The operational key-value store continues serving application lookups; PuppyGraph supplies relationship exploration over the supported tables.

![PuppyGraph customer logos under the heading Trusted by.](https://o6xswp5m6ilbks2z.public.blob.vercel-storage.com/uploads/ab8e18ef4ebebeddc0b3152c/4b17a9ad-9bbb-4dba-b342-1ebf59630ba0/snowflake-zero-copy-clone-figure-3-070c58edc4.png)

![PuppyGraph customer testimonials from Trend Micro, Palo Alto Networks, Sola Security, Netskope, Coinbase, and Baker Hughes.](https://o6xswp5m6ilbks2z.public.blob.vercel-storage.com/uploads/ab8e18ef4ebebeddc0b3152c/8f2946c8-ecd0-4f10-adcb-cb2c9c6ca379/snowflake-zero-copy-clone-figure-4-65c2a94de2.png)

## Conclusion

Key-value pairs associate identifiers with information across code, JSON, APIs, and databases. They work well when the application knows the key it needs. Broader searches and investigations require additional structure: indexes, relational queries, or modeled relationships that help an agent determine what evidence to retrieve next.

Try the forever-free [PuppyGraph Developer Edition](https://www.puppygraph.com/download-confirmation) and [book a demo](https://www.puppygraph.com/book-demo) with the team to see how openCypher and Gremlin queries connect warehouse and lakehouse tables, with no graph-specific ETL, so agents can investigate the relationships behind delivery problems.
