Python Forum
Create new dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Create new dictionary (/thread-37151.html)



Create new dictionary - angus1964 - May-06-2022

If I have the following two dictionaries.

person1 = {
    "name" : "fred"
    "age" : 31
}

person2 = {
    "name" : "bob"
    "age" : 35
}
Can I easily create

person = {
   "name" : ("fred", "bob")
   "age" :(31, 35)
}



RE: Create new dictionary - ibreeden - May-06-2022

(May-06-2022, 07:05 AM)angus1964 Wrote: Can I easily create ...
Sure you can, you just showed how to do it. But what are you trying to accomplish? At first sight it does not seem to be practical.


RE: Create new dictionary - angus1964 - May-06-2022

(May-06-2022, 10:25 AM)ibreeden Wrote:
(May-06-2022, 07:05 AM)angus1964 Wrote: Can I easily create ...
Sure you can, you just showed how to do it. But what are you trying to accomplish? At first sight it does not seem to be practical.

The main thing I am asking is there a way to merge the first two dictionaries to create the third one, ideally the values would be in a tuple as I'm looking to pass it into a Pandas dataframe to use in Tkinter.


RE: Create new dictionary - snippsat - May-06-2022

(May-06-2022, 12:11 PM)angus1964 Wrote: he main thing I am asking is there a way to merge the first two dictionaries to create the third one
Eg with defaultdict
from collections import defaultdict

def merge_dicts(*dicts):
    merged = defaultdict(list)
    for d in dicts:
        for k, v in d.items():
            merged[k].append(v)
    return merged

if __name__ == '__main__':
    person1 = {
        "name" : "fred",
        "age" : 31
    }
    person2 = {
        "name" : "bob",
        "age" : 35
    }
    person = merge_dicts(person1, person2)
    print(person)
Output:
defaultdict(<class 'list'>, {'name': ['fred', 'bob'], 'age': [31, 35]})
(May-06-2022, 12:11 PM)angus1964 Wrote: ideally the values would be in a tuple as I'm looking to pass it into a Pandas dataframe
>>> import pandas as pd
>>> 
>>> df = pd.DataFrame.from_dict(person)
>>> df
   name  age
0  fred   31
1   bob   35



RE: Create new dictionary - angus1964 - May-07-2022

(May-06-2022, 12:44 PM)snippsat Wrote:
(May-06-2022, 12:11 PM)angus1964 Wrote: he main thing I am asking is there a way to merge the first two dictionaries to create the third one
Eg with defaultdict
from collections import defaultdict

def merge_dicts(*dicts):
    merged = defaultdict(list)
    for d in dicts:
        for k, v in d.items():
            merged[k].append(v)
    return merged

if __name__ == '__main__':
    person1 = {
        "name" : "fred",
        "age" : 31
    }
    person2 = {
        "name" : "bob",
        "age" : 35
    }
    person = merge_dicts(person1, person2)
    print(person)
Output:
defaultdict(<class 'list'>, {'name': ['fred', 'bob'], 'age': [31, 35]})
(May-06-2022, 12:11 PM)angus1964 Wrote: ideally the values would be in a tuple as I'm looking to pass it into a Pandas dataframe
>>> import pandas as pd
>>> 
>>> df = pd.DataFrame.from_dict(person)
>>> df
   name  age
0  fred   31
1   bob   35

Many thanks Snippsat, exactly what I was looking for. Smile Smile


RE: Create new dictionary - perfringo - May-08-2022

If objective is to get data into dataframe then there are also following alternatives:

- using .from_dict and .append:

first = {"name": "fred", "age" : 31}
second = {"name": "bob", "age" : 35}

df = pd.DataFrame.from_dict([first],
                            orient="columns").append(pd.DataFrame.from_dict([second]), ignore_index=True)

# df would be:
   name  age
0  fred   31
1   bob   35
However, this is long, ugly and append method is deprecated. Same result can be achieved using concat

df_x = pd.DataFrame.from_dict([first],orient="columns")
df_y = pd.DataFrame.from_dict([second], orient="columns")

df = pd.concat([df_x, df_y], ignore_index=True)
Same problems as with first example. This is not scalable, it works only in case of two dictionaries. For arbitrary number of dictionaries they must be in container. Then we can create stream (generator) and feed it to concat:

persons = [{"name": "fred", "age": 31},
           {"name": "bob", "age": 35},
           {"name": "alice", "age": 33}]

stream = (pd.DataFrame.from_dict((person,), orient="columns") for person in persons)

df = pd.concat(stream, ignore_index=True)

# df would be
    name  age
0   fred   31
1    bob   35
2  alice   33



RE: Create new dictionary - snippsat - May-08-2022

(May-08-2022, 11:47 AM)perfringo Wrote: However, this is long, ugly and append method is deprecated. Same result can be achieved using concat
Or as i do merge dicts with defaultdict before give to Pandas.
Then as you see in my code it short like this.
df = pd.DataFrame.from_dict(person)