Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create new dictionary
#1
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)
}
Reply
#2
(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.
Reply
#3
(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.
Reply
#4
(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
Reply
#5
(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
Reply
#6
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
(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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Create new dictionary angus1964 2 1,272 May-06-2022, 02:14 PM
Last Post: deanhystad
  Create a dynamic Menu from a editable Dictionary. KiNeMs 1 2,306 Jan-28-2020, 04:27 AM
Last Post: Larz60+
  Need to create a dictionary from a *.csv 74razor 5 3,030 Dec-18-2019, 08:57 PM
Last Post: ichabod801
  Create a dictionary from a list klllmmm 3 2,968 Oct-06-2019, 05:50 PM
Last Post: Gribouillis
  Create XML from dictionary pygrrrl 7 105,122 Jul-29-2019, 08:33 PM
Last Post: pygrrrl
  Better way to create nested dictionary with defaultdict() x2mlh 8 21,688 Nov-30-2017, 08:10 PM
Last Post: buran
  create dictionary from **kwargs that include tuple bluefrog 2 4,891 Oct-26-2016, 10:24 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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