Convert a python dictionary with sets' values to a binary dataframe - TagMerge
3Convert a python dictionary with sets' values to a binary dataframeConvert a python dictionary with sets' values to a binary dataframe

Convert a python dictionary with sets' values to a binary dataframe

Asked 1 years ago
1
3 answers

You can use pd.str.get_dummies, like this:

my_dict = {1: {'a', 'b'}, 2: {'a', 'c'}, 3: {'b', 'c', 'd'}, 4: {'a'}}
ser = pd.Series({k: list(v) for k, v in my_dict.items()}).str.join('|').str.get_dummies()
print(ser)

Source: link

0

Can you please tell me if there is a better way to do this?
people = {'123456':{'first': 'Bob', 'last':'Smith'},
          '2345343': {'first': 'Jim', 'last': 'Smith'}}

names = list()
first_names= set()
last_names = set()
for device in people:
    names.append(device)
    first_names.add(people[device]['first'])
    last_names.add(people[device]['last'])
The only possible improvement I see is to avoid unnecessary dictionary lookups by iterating over key-value pairs:
ids = list()
first_names = set()
last_names = set()

for person_id, details in people.items():
    ids.append(person_id)
    first_names.add(details['first'])
    last_names.add(details['last'])
Instead of appending the id's one by one, I would use:
ids = list(people.keys())
Then you can change your the rest of your code to:
first_names = set()
last_names = set()

for details in people.values():
     first_names.add(details['first'])
     last_names.add(details['last'])
Use set comprehension:
first_names = {v['first'] for v in people.values()}
last_names = {v['last'] for v in people.values()}
ids=list(people.keys())

Source: link

0

Syntax
dictionary.fromkeys(keys, value)
Python How to Convert Python Set to Dictionary By Krunal Last updated Dec 31, 2020 0
i_set = {'Vlad Tepes', 'Alucard', 'Trevor', 'Isaac', 'Carmilla'}
print(i_set)
print(type(i_set))

# converting set to dictionary
dictionary = dict.fromkeys(i_set, 0)

# printing final result and its type
print(dictionary)
print(type(dictionary))
Output
{'Alucard', 'Isaac', 'Trevor', 'Vlad Tepes', 'Carmilla'}
<class 'set'>
{'Alucard': 0, 'Isaac': 0, 'Trevor': 0, 'Vlad Tepes': 0, 'Carmilla': 0}
<class 'dict'>
Python dict() method can be used to take input parameters and convert them into a dictionary. We also need to use the zip() function to group the keys and values, which finally becomes the key-value pair of the dictionary.
set_keys = {'Vlad Tepes', 'Alucard', 'Trevor', 'Isaac'}
set_values = {1, 2, 3, 4}

# converting set to dictionary
dictionary = dict(zip(set_keys, set_values))

# printing final result and its type
print(dictionary)
print(type(dictionary))
Output
{'Vlad Tepes': 1, 'Isaac': 2, 'Trevor': 3, 'Alucard': 4}
<class 'dict'>

Source: link

Recent Questions on python

    Programming Languages