Recent Tutorials and Articles
    Merging two arrays in a dictionary in Python
    Published on: 2018-09-08 09:09:45
    Posted By: Amit Kumar

    This tutorial explains how to merge an array containing label and other one containing data into a dictionary in Python

    Abstract


    We sometimes come across a situation where we have labels (or headers) in an array while data for these are in another set of arrays. However, in order to pass this data around, we normally use JSON format that requires a dictionary like data structure containing mapping of label to its correspoding data attributes.

     

    Implementation


    Typical way of doing it is to iterate over set of Arrays containing data and then creating a dictionary containing key from labels array and value from data array.

    However, python makes it super easy to deal with, using a combination of zip and dict method as shown in below program -

    labels = ['tutorialName','tutorialCateogry']
    
    data = [
        ['Merging Arrays', 'Python Basics'],
        ['Developing Consumers', 'Apache Kafka']
    ]
    
    print [dict(zip(labels, datum)) for datum in data]

    Here is the output that this program generates -

    [{'tutorialCateogry': 'Python Basics', 'tutorialName': 'Merging Arrays'}, {'tutorialCateogry': 'Apache Kafka', 'tutorialName': 'Developing Consumers'}]

     

     

     

     

     

    Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.

    Posted By: Amit Kumar
    Published on: 2018-09-08 09:09:45

    Comment Form is loading comments...