Prepin
Log in

Simplify a Dictionary.

Approach / Explanation

In this task, you need to create a function or method that 'flattens' a dictionary. Here, a dictionary refers to a specific data structure, also known as a key-value store, commonly used in programming. Flattening a dictionary means transforming a dictionary that contains other dictionaries as some of its values into a standard dictionary (where all keys are of a basic data type and cannot be nested). In this process, composite keys are formed by concatenating the keys of the inner dictionaries with the key of the outer dictionary, using periods as separators. This operation should not alter the original dictionary; instead, it must return a new dictionary with the flattened key-value pairs. This task will require a solid understanding of dictionaries, recursive function calls, and string manipulation.

Suggested Answer

For example, let's look at this Python code that flattens a nested dictionary: def flatten_dict ( d , parent_key = '' , sep = '.' ) : items = [ ] for k , v in d . items ( ) : new_key = f" { parent_key } { sep } { k } " if parent_key else k if isinstance ( v , dict ) : items . extend ( flatten_dict ( v , new_key , sep ) . items ( ) ) else : items . append ( ( new_key , v ) ) return dict ( items ) nested_dictionary = { 'key' : 3 , 'foo' : { 'a' : 5 , 'bar' : { 'baz' : 8 } } } print ( flatten_dict ( nested_dictionary ) ) This code iterates through the dictionary's items. If a value is another dictionary, it recursively calls the flatten_dict() function with the current key combined as the parent key. If the value is not a dictionary, it simply appends the key-value pair to the items list. Ultimately, the items list is transformed into a dictionary and returned. This process flattens the nested_dictionary , resulting in: {'key': 3, 'foo.a': 5, 'foo.bar.baz': 8} .

Alternative Answer

Let's take a look at another instance of flattening a dictionary in JavaScript. function flattenDict ( dict , parent = "" , result = { } ) { for ( let key in dict ) { let newKey = parent ? ` ${ parent } . ${ key } ` : key ; if ( typeof dict [ key ] === 'object' && dict [ key ] !== null ) { flattenDict ( dict [ key ] , newKey , result ) ; } else { result [ newKey ] = dict [ key ] ; } } return result ; } let nestedDictionary = { "key" : 3 , "foo" : { "a" : 5 , "bar" : { "baz" : 8 } } } ; console . log ( flattenDict ( nestedDictionary ) ) ; This JavaScript function operates similarly to its Python counterpart, despite some differences in syntax. It flattens the nestedDictionary and yields: {key: 3, 'foo.a': 5, 'foo.bar.baz': 8} .

Question Details

Difficulty & Category

Medium
data structures

Product

AI Candidate AgentCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin | All rights reserved.