Convert list of tuples and list to dictionary - python

I have a list of tuples
data = [(2015-10-08,2016-07-17,2015-09-09,2014-01-29),(Alex, Jerry, Tony, Tom), (5,6,7,8)]
And I have a list, this list contains column headings.
title = [Date , Name, Age]
With this list and list of tuples I want a dictionary.
This is the expected output
output = {1:{'Date': 2015-10-08,2016-07-17,2015-09-09,2014-01-29} ,{'Name' : Alex, Jerry, Tony, Tom}, {'Age' : 5,6,7,8}}

Try this:
dict(zip(title, data))
Or for making them sets:
dict(zip(title, map(set, data)))

Try :
output = {}
output["Date"] = set(data[0])
output["Name"] = set(data[1])
output["Age"] = set(data[2])

data = [('2015-10-08','2016-07-17,2015-09-09','2014-01-29'),('Alex', 'Jerry', 'Tony', 'Tom'), (5,6,7,8)]
title = ['Date', 'Name', 'Age']
your_dict = {key: value for key, value in zip(title, data)}

Here is one of the solutions:
data = [('2015-10-08','2016-07-17','2015-09-09','2014-01-29'),('Alex', 'Jerry', 'Tony', 'Tom'), ('5','6','7','8')]
title = ['Date', 'Name', 'Age']
output = {}
for i in range(len(title)):
output[i+1] = {title[i]: ",".join(data[index])}
print (output)
Output:
{1: {'Date': '2015-10-08,2016-07-17,2015-09-09,2014-01-29'}, 2: {'Name': '2015-10-08,2016-07-17,2015-09-09,2014-01-29'}, 3: {'Age': '2015-10-08,2016-07-17,2015-09-09,2014-01-29'}}

Related

Flatten list of dictionaries with multiple key, value pairs

I have a list of dictionaries with multiple KVP each
list_dict = [{'id': 1, 'name': 'sana'}, {'id': 2, 'name': 'art'}, {'id': 3, 'name': 'tiara'}]
I want to transform this into this format:
final_dict = {1: 'sana', 2: 'art', 3: 'tiara'}
I've been trying dict comprehensions but it does not work. Here's the best that I could do:
{k:v for d in list_dict for k, v in d.items()}
You don't need d.items(), you can just access the id and name properties of each dict.
{d['id']: d['name'] for d in list_dict}
for each element of the list you want the d["id"] to be the key and d["name"] to be the value, so the dictionary comprehension would look like this:
{d["id"]: d["name"] for d in list_dict}
You can try
final_dict={}
for dico in list_dict:
final_dict[dico['id']] = dico['name']
There's probably a few different ways you can do this. Here's a nice simple way of doing it using a pandas dataframe:
import pandas as pd
df = pd.DataFrame(list_dict) # <- convert to dataframe
df = df.set_index('id') # <- set the index to the field you want as the key
final_dict = df['name'].to_dict() # <- convert the series 'name' to a dict
print(final_dict)
{1: 'sana', 2: 'art', 3: 'tiara'}

Easier way to transform multiple lists into a dictionary?

Right now, I have this very clunky dictionary:
input_data = {'names': 'Elizabeth,Emily,Grant', 'titles': 'Sales,Accounting,Operations'}
nameList = input_data['names'].split(',')
titleList = input_data['titles'].split(',')
d1 = dict()
d2 = dict()
for val in nameList:
d1.setdefault('Name', []).append(val)
for val in titleList:
d2.setdefault('Title', []).append(val)
fullDict = dict(d1, **d2)
I'm convinced there's a better way to covert this:
{'names': 'Elizabeth,Emily,Grant', 'titles': 'Sales,Accounting,Operations'}
Into this:
{'Name': ['Elizabeth', 'Emily', 'Grant'],
'Title': ['Sales', 'Accounting', 'Operations']}
This simple dictionary comprehension seemed to produce the result you wanted.
{x: y.split(',') for x, y in input_data.items()}
If the name part is also important, then I think this should work.
{x.title()[:-1] if x[-1] == 's' else x.title(): y.split(',') for x, y in input_data.items()}
So you want to accomplish two things: Split the values in the original dictionary, and rename the keys in the original dictionary. You can do everything in-place, as opposed to creating new dictionaries.
input_data = {'names': 'Elizabeth,Emily,Grant', 'titles': 'Sales,Accounting,Operations'}
input_data['Name'] = input_data['names'].split(',')
input_data['Title'] = input_data['titles'].split(',')
del input_data['names'], input_data['titles']
print(input_data)
Returns the output:
{'Name': ['Elizabeth', 'Emily', 'Grant'], 'Title': ['Sales', 'Accounting', 'Operations']}

Convert a string to list of dictionaries

I have a string as below
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
If you see clearly its kind of 2 dictionaries
rule:unique,attribute:geo,name:unq1
and
rule:sum,attribute:sales,name:sum_sales
I want to convert them to as below
[
{'rule': 'sum', 'attribute': 'sales', 'name': 'sum_sales'},
{'rule': 'unique', 'attribute': 'geo', 'name': 'uniq1'}
]
Kindly help
I tried
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
dlist=[]
at_rule_gm=(x.split(':') for x in gmr.split(','))
dict(at_rule_gm)
but here I get only the last dictionary.
Start with sample of OP:
>>> gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
Make an empty list first.
>>> dlist = [ ]
Loop with entry over list, yielded by gmr.split(','),
Store entry.split(':') into pair,
Check whether first value in pair (the key) is 'rule'
If so, append a new empty dictionary to dlist
Store pair into last entry of dlist:
>>> for entry in gmr.split(','):
pair = entry.split(':')
if pair[0] == 'rule':
dlist.append({ })
dlist[-1][pair[0]] = pair[1]
Print result:
>>> print(dlist)
[{'name': 'unq1', 'attribute': 'geo', 'rule': 'unique'},
{'name': 'sum_sales', 'attribute': 'sales', 'rule': 'sum'}]
Looks like what OP intended to get.
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
split_str = gmr.split(',')
dlist = []
for num in range(0, len(split_str),3):
temp_dict = {}
temp1 = split_str[num]
temp2 = split_str[num+1]
temp3 = split_str[num+2]
key,value = temp1.split(':')
temp_dict.update({key:value})
key,value = temp2.split(':')
temp_dict.update({key:value})
key,value = temp3.split(':')
temp_dict.update({key:value})
dlist.append(temp_dict)
dict always gives a single dictionary, not a list of dictionaries. For the latter, you can use a list comprehension after first splitting by 'rule:':
gmr = 'rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
items = (f'rule:{x}' for x in filter(None, gmr.split('rule:')))
res = [dict(x.split(':') for x in item.split(',') if x) for item in items]
print(res)
# [{'attribute': 'geo', 'name': 'unq1', 'rule': 'unique'},
# {'attribute': 'sales', 'name': 'sum_sales', 'rule': 'sum'}]

Appending a list in a dictionary with a value of index of a list

I have a dictionary and a list:
results = {"Alice":[], "Bob":[], "Clare":[], "Dennis":[], "Eva":[]}
list_of_names = ['Bob', 'Alice', 'Clare', 'Eva', 'Dennis']
and I want to fill those lists with a value of index+1 accordingly.
So that if we have the list above the dictionary would look like this
results = {"Alice":[2], "Bob":[1], "Clare":[3], "Dennis":[5], "Eva":[4]}
this is my current code
Aindex = list_of_names.index("Alice")
Bindex = list_of_names.index("Bob")
Cindex = list_of_names.index("Clare")
Dindex = list_of_names.index("Dennis")
Eindex = list_of_names.index("Eva")
Aindex = Aindex + 1
Bindex = Bindex + 1
Cindex = Cindex + 1
Dindex = Dindex + 1
Eindex = Eindex + 1
results["Alice"].append(Aindex)
results["Bob"].append(Bindex)
results["Clare"].append(Cindex)
results["Dennis"].append(Dindex)
results["Eva"].append(Eindex)
Is there any way to shorten this code and make it work for any amount of dictionary/list entries?
yes. One line with dictionary comprehension and enumerate starting at 1:
list_of_names = ['Bob', 'Alice', 'Clare', 'Eva', 'Dennis']
results = {name:[i] for i,name in enumerate(list_of_names,1)}
>>> results
{'Alice': [2], 'Bob': [1], 'Clare': [3], 'Dennis': [5], 'Eva': [4]}
If you want to use the existing list inside the dict
results = {"Alice":[], "Bob":[], "Clare":[], "Dennis":[], "Eva":[]}
list_of_names = ['Bob', 'Alice', 'Clare', 'Eva', 'Dennis']
for i,j in enumerate(list_of_names,1):
results[j].append(i)

return a key value pair fro a list of lists in python

I have a list of lists: myList = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]
Would like to return a dictionary with key, value pairs dict={make:'Ford',model:'Mustang',......}
d ={}
for row in myList:
for col in row:
d[col]=row[1]
This returns the first key value pair correct {'make':'Ford','Ford':'Ford','model':'Mustang','Mustang':'Mustang'...} but then it repeats the second value.
Just use the built-in dict funtion
myList = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]
d = dict(myList)
d={}
for row in myList:
d[row[0]] = row[1]
This is how you’d do this if you want to use loops, but you can also just d = dict(myList) to cast the list to a dict.
You can try this:
myList = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]
final_dict = {a:b for a, b in myList}
Output:
{'make': 'Ford', 'model': 'Mustang', 'year': 1964}

Categories