Python Forum
Create Dict from multiple Lists with duplicate Keys
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create Dict from multiple Lists with duplicate Keys
#2
you are showing ellipsis in your data. In the following solution, I am assuming that this is an error.
from CreateDict import CreateDict

desigName = ['Catching Fireflies', 'Spoonflower Color Map', 'Night Sky Stars Midnight Blue']
creatorName = ['thestorysmith', 'spoonflower_help', 'at_the_cottage']
fabric_names = ['FABRIC_PETAL_SIGNATURE_COTTON', 'FABRIC_SATIN', 'FABRIC_COTTON_POPLIN_BRAVA']
data = [
    ('FABRIC_PETAL_SIGNATURE_COTTON', 1.75, 10.58, 18.22),
    ('FABRIC_PETAL_SIGNATURE_COTTON', 1.75, 10.58, 18.22),
    ('FABRIC_PETAL_SIGNATURE_COTTON', 1.75, 10.58, 18.22), 
    ('FABRIC_SATIN', 1.75, 11.85, 19.71),
    ('FABRIC_SATIN', 1.75, 11.85, 19.71),
    ('FABRIC_SATIN', 1.75, 11.85, 19.71), 
    ('FABRIC_COTTON_POPLIN_BRAVA', 1.75, 11.85, 19.71),
    ('FABRIC_COTTON_POPLIN_BRAVA', 1.75, 11.85, 19.71),
    ('FABRIC_COTTON_POPLIN_BRAVA', 1.75, 11.85, 19.71)
]

def create_new_dict():
    newdict = {}
    cd = CreateDict()
    for n, item in enumerate(desigName):
        dnode = cd.add_node(newdict, (item, creatorName[n]))
        cd.add_cell(dnode, f"fabric_name{n:02}", fabric_names[n])
        for element in data:
            if element[0] == fabric_names[n]:
                cd.add_cell(dnode, f"test_swatch_meter_{n:02}", element[1])
                cd.add_cell(dnode, f"fat_quarter_meter__{n:02}", element[2])
                cd.add_cell(dnode, f"meter_{n:02}", element[3])
                break
    cd.display_dict(newdict)

create_new_dict()   
this creates (which is what you ask for):
Output:
{ ('Catching Fireflies', 'thestorysmith'): { 'fabric_name00': 'FABRIC_PETAL_SIGNATURE_COTTON', 'test_swatch_meter_00': 1.75, 'fat_quarter_meter__00': 10.58, 'meter_00': 18.22 }, ('Spoonflower Color Map', 'spoonflower_help'): { 'fabric_name01': 'FABRIC_SATIN', 'test_swatch_meter_01': 1.75, 'fat_quarter_meter__01': 11.85, 'meter_01': 19.71 }, ('Night Sky Stars Midnight Blue', 'at_the_cottage'): { 'fabric_name02': 'FABRIC_COTTON_POPLIN_BRAVA', 'test_swatch_meter_02': 1.75, 'fat_quarter_meter__02': 11.85, 'meter_02': 19.71 } }
Also, why is the data repeated for each fabric? I take care of this, but only one entry is necessary, and would simplify the code

To make a better dictionary:

if data were: data = [('FABRIC_PETAL_SIGNATURE_COTTON', 1.75, 10.58, 18.22)('FABRIC_SATIN', 1.75, 11.85, 19.71),('FABRIC_COTTON_POPLIN_BRAVA', 1.75, 11.85, 19.71),('FABRIC_COTTON_POPLIN_BRAVA', 1.75, 11.85, 19.71)]

then this code would work:
from CreateDict import CreateDict

desigName = ['Catching Fireflies', 'Spoonflower Color Map', 'Night Sky Stars Midnight Blue']
creatorName = ['thestorysmith', 'spoonflower_help', 'at_the_cottage']
fabric_names = ['FABRIC_PETAL_SIGNATURE_COTTON', 'FABRIC_SATIN', 'FABRIC_COTTON_POPLIN_BRAVA']
data = [
    ('FABRIC_PETAL_SIGNATURE_COTTON', 1.75, 10.58, 18.22),
    ('FABRIC_SATIN', 1.75, 11.85, 19.71),
    ('FABRIC_COTTON_POPLIN_BRAVA', 1.75, 11.85, 19.71)
]

def create_new_dict():
    newdict = {}
    cd = CreateDict()
    for n, item in enumerate(desigName):
        dnode = cd.add_node(newdict, (item, creatorName[n]))
        cnode = cd.add_node(dnode, fabric_names[n])
        element =  data[n]
        cd.add_cell(cnode, f"test_swatch_meter", element[1])
        cd.add_cell(cnode, f"fat_quarter_meter", element[2])
        cd.add_cell(cnode, f"meter_", element[3])

    return newdict

newdict = create_new_dict()
print(newdict)
which creates a much better dictionary:
Output:
{ ('Catching Fireflies', 'thestorysmith'): { 'FABRIC_PETAL_SIGNATURE_COTTON': { 'test_swatch_meter': 1.75, 'fat_quarter_meter': 10.58, 'meter_': 18.22 } }, ('Spoonflower Color Map', 'spoonflower_help'): { 'FABRIC_SATIN': { 'test_swatch_meter': 1.75, 'fat_quarter_meter': 11.85, 'meter_': 19.71 } }, ('Night Sky Stars Midnight Blue', 'at_the_cottage'): { 'FABRIC_COTTON_POPLIN_BRAVA': { 'test_swatch_meter': 1.75, 'fat_quarter_meter': 11.85, 'meter_': 19.71 } } }
For either of these solutions, you will have to add the following module to the same directory as your script
you are free to use this as I have published it before please use the name indicated:

CreateDict.py:
# 
import os

class CreateDict:
    """
    Generic Software tools used by Trailmapper.

    CreateDict.py - Contains methods to simplify node and cell creation within
                    a dictionary

    Usage: 
    
        The best way to learn what can be done is to examine the testit function
        included in this module.

        new_dict(dictname) - Creates a new dictionary instance with the name
            contained in dictname

        add_node(parent, nodename) - Creates a new node (nested dictionary)
            named in nodename, in parent dictionary.

        add_cell(nodename, cellname, value) - Creates a leaf node within node
            named in nodename, with a cell name of cellname, and value of value.

        display_dict(dictname) - Recursively displays a nested dictionary.

    Requirements:

        Trailmapper software:
            None

        Python standard library:
            os
    
    Author: Larry McCaig  -- May 2019.
    """
    def __init__(self):
        os.chdir(os.path.abspath(os.path.dirname(__file__)))

    def new_dict(self, dictname):
        setattr(self, dictname, {})

    def add_node(self, parent, nodename):
        node = parent[nodename] = {}
        return node

    def add_cell(self, nodename, cellname, value):
        cell =  nodename[cellname] = value
        return cell

    def display_dict(self, dictname, level=0):
        indent = " " * (4 * level)
        for key, value in dictname.items():
            if isinstance(value, dict):
                print(f'\n{indent}{key}')
                level += 1
                self.display_dict(value, level)
            else:
                print(f'{indent}{key}: {value}')
            if level > 0:
                level -= 1


def testit():
    # instantiate class
    cd = CreateDict()

    # create new dictionary named CityList
    cd.new_dict('CityList')

    # add node Boston
    boston = cd.add_node(cd.CityList, 'Boston')
    # add sub node Resturants
    bos_resturants = cd.add_node(boston, 'Resturants')

    # Add subnode 'Spoke Wine Bar' to parent bos_resturants
    spoke = cd.add_node(bos_resturants, 'Spoke Wine Bar')
    cd.add_cell(spoke, 'Addr1', '89 Holland St')
    cd.add_cell(spoke, 'City', 'Sommerville')
    cd.add_cell(spoke, 'Addr1', '02144')
    cd.add_cell(spoke, 'Phone', '617-718-9463')

    # Add subnode 'Highland Kitchen' to parent bos_resturants
    highland = cd.add_node(bos_resturants, 'Highland Kitchen')
    cd.add_cell(highland, 'Addr1', '150 Highland Ave')
    cd.add_cell(highland, 'City', 'Sommerville')
    cd.add_cell(highland, 'ZipCode', '02144')
    cd.add_cell(highland, 'Phone', '617-625-1131')

    # display dictionary
    print(f'\nCityList Dictionary')
    cd.display_dict(cd.CityList)
    print(f'\nraw data: {cd.CityList}')

if __name__ == '__main__':
    testit()
Reply


Messages In This Thread
RE: Create Dict from multiple Lists with duplicate Keys - by Larz60+ - Jun-23-2021, 05:21 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  python convert multiple files to multiple lists MCL169 6 1,837 Nov-25-2023, 05:31 AM
Last Post: Iqratech
  Find duplicate files in multiple directories Pavel_47 9 3,623 Dec-27-2022, 04:47 PM
Last Post: deanhystad
  Create multiple/single csv file for each sql records mg24 6 1,597 Sep-29-2022, 08:06 AM
Last Post: buran
  Updating nested dict list keys tbaror 2 1,392 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Loop Dict with inconsistent Keys Personne 1 1,715 Feb-05-2022, 03:19 AM
Last Post: Larz60+
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 3,006 Aug-11-2021, 03:45 PM
Last Post: jamesaarr
  Better way to append frames from a video to multiple lists? Balaganesh 0 1,957 May-13-2021, 07:37 AM
Last Post: Balaganesh
  Xlsxwriter: Create Multiple Sheets Based on Dataframe's Sorted Values KMV 2 3,683 Mar-09-2021, 12:24 PM
Last Post: KMV
Question How to print multiple elements from multiple lists in a FOR loop? Gilush 6 3,172 Dec-02-2020, 07:50 AM
Last Post: Gilush
  Create a sequential number (counter) and reset at each duplicate Mekala 0 1,822 Sep-20-2020, 05:02 AM
Last Post: Mekala

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020