how do I build a dictionary data inside a list? - python

I have this program:
def file(fname):
lines = open(fname).read().splitlines()
return(lines)
print(file('venue.txt'))
And it came out like this which I change into list:
['room 1, 10, 250']
How do I build a dictionary data with it, so that it can be like this:
[{'name': 'room 1', 'max': 10, 'cost': 250}]
Some clue maybe for me to build it.
Thanks
Edited:
def file(fname):
lines = open(fname).read().splitlines()
new = []
for i in lines:
split = i.split(', ')
new.append({'name':split[0],'max':split[1],'cost':split[2]})
return(new)
print(file('venue.txt'))
It prints:
new.append({'name':split[0],'max':split[1],'cost':split[2]})
IndexError: list index out of range
What does it mean?

You can try this:
import re
def file(fname):
lines = open(fname).read().splitlines()
return(lines)
headers = ["name", "max", "cost"]
data1 = [re.split(",\s+", i) for i in file("venue.txt")]
final_data = [{a:b for a, b in zip(headers, data} for data in data1]
print(final_data)

If they are separated by ', ' you can use the split() on ', '.
Will return an array with the separated items.
For your example:
current_list = ['room 1, 10, 250']
split = current_list[0].split(', ')
new_list = [{'name': split[0], 'max': int(split[1]), 'cost': int(split[2])}]
print(new_list)
output:
[{'name': 'room 1', 'max': 10, 'cost': 250}]
For a larger list:
current_list = ['room 1, 10, 250', 'room 2, 30, 500','room 3, 50, 850']
new_list = []
for i in current_list:
split = i.split(', ')
new_list.append({'name': split[0], 'max': int(split[1]), 'cost': int(split[2])})
print(new_list)
output:
[{'name': 'room 1', 'max': 10, 'cost': 250}, {'name': 'room 2', 'max': 30, 'cost': 500}, {'name': 'room 3', 'max': 50, 'cost': 850}]

Related

how to insert list of elements into list of dictionaries

I have one list of elements and another list of dictionaries and i want to insert list of elements into each dictionary of list
list_elem = [1,2,3]
dict_ele = [{"Name":"Madhu","Age":25},{"Name":"Raju","Age:24},{""Name":"Mani","Age":12}],
OUTPUT As:
[{"ID":1,"Name":"Madhu","Age":25},{"ID":2,"Name":"Raju","Age:24},{"ID":3,"Name":"Mani","Age":12}]
I have tried this way :
dit = [{"id":item[0]} for item in zip(sam)]
# [{"id":1,"id":2,"id":3}]
dic1 = list(zip(dit,data))
print(dic1)
# [({"id":1},{{"Name":"Madhu","Age":25}},{"id":2},{"Name":"Raju","Age:24},{"id":3},{""Name":"Mani","Age":12})]
What is the most efficient way to do this in Python?
Making an assumption here that the OP's original question has a typo in the definition of dict_ele and also that list_elem isn't really necessary.
dict_ele = [{"Name":"Madhu","Age":25},{"Name":"Raju","Age":24},{"Name":"Mani","Age":12}]
dit = [{'ID': id_, **d} for id_, d in enumerate(dict_ele, 1)]
print(dit)
Output:
[{'ID': 1, 'Name': 'Madhu', 'Age': 25}, {'ID': 2, 'Name': 'Raju', 'Age': 24}, {'ID': 3, 'Name': 'Mani', 'Age': 12}]
dict_ele = [{"Name":"Madhu","Age":25},{"Name":"Raju","Age":24},{"Name":"Mani","Age":12}]
list_elem = [1,2,3]
[{'ID': id, **_dict} for id, _dict in zip(list_elem, dict_ele)]
[{'ID': 1, 'Name': 'Madhu', 'Age': 25}, {'ID': 2, 'Name': 'Raju', 'Age': 24}, {'ID': 3, 'Name': 'Mani', 'Age': 12}]
try this: r = [{'id':e[0], **e[1]} for e in zip(list_elem, dict_ele)]

Convert a text file into a dictionary list

I have a text file in this format (in_file.txt):
banana 4500 9
banana 350 0
banana 550 8
orange 13000 6
How can I convert this into a dictionary list in Python?
Code:
in_filepath = 'in_file.txt'
def data_dict(in_filepath):
with open(in_filepath, 'r') as file:
for line in file.readlines():
title, price, count = line.split()
d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)
return [d]
The terminal shows the following result:
{'title': 'orange', 'price': 13000, 'count': 6}
Correct output:
{'title': 'banana', 'price': 4500, 'count': 9}, {'title': 'banana', 'price': 350, 'count': 0} , ....
Can anyone help me with my problem? Thank you!
titles = ["title","price","count"]
[dict(zip(titles, [int(word) if word.isdigit() else word for word in line.strip().split()])) for line in open("in_file.txt").readlines()]
or:
titles = ["title","price","count"]
[dict(zip(titles, [(data:=line.strip().split())[0], *map(int, data[1:])])) for line in open("in_file.txt").readlines()]
your approach(corrected):
in_filepath = 'in_file.txt'
def data_dict(in_filepath):
res = []
with open(in_filepath, 'r') as file:
for line in file.readlines():
title, price, count = line.split()
d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)
res.append(d)
return res
data_dict(in_filepath)
why? because
->
d = {}
d['title'] = title
d['price'] = int(price)
d['count'] = int(count)
is out of for loop and run only once and when ‍‍for be finished and then you have just one element
you return your last element and didn't use others and use must create a list and append every element at the last line of for loop (saving) and at last, return result
#Rockbar approach:
import pandas as pd
list(pd.read_csv("in_file.txt", sep=" ", header=None, names=["title","price","count"]).T.to_dict().values())
You can read the file line-by-line and then create dict base keys that define in the first.
keys = ['title', 'price' , 'count']
res = []
with open('in_file.txt', 'r') as file:
for line in file:
# Or in python >= 3.8
# while (line := file.readline().rstrip()):
tmp = [int(w) if w.isdigit() else w for w in line.rstrip().split() ]
res.append(dict(zip(keys, tmp)))
print(res)
[
{'title': 'banana', 'price': 4500, 'count': 9},
{'title': 'banana', 'price': 350, 'count': 0},
{'title': 'banana', 'price': 550, 'count': 8},
{'title': 'orange', 'price': 13000, 'count': 6}
]
You are trying to create a list of dictionaries (array of objects). So it would be best if you appended dictionary into a list each time you created it from a line of text.
Code
in_filepath = 'in_file.txt'
def data_dict(in_filepath):
dictionary = []
with open(in_filepath, 'r') as file:
for line in file:
title, price, count = line.split()
dictionary.append({'title': title, 'price': int(price), 'count': int(count)})
return dictionary
print(data_dict(in_filepath))
Output
[
{"title": "banana", "price": 4500, "count": 9},
{"title": "banana", "price": 350, "count": 0 },
{"title": "banana", "price": 550, "count": 8},
{"title": "orange", "price": 13000, "count": 6}
]

How can I filter the lists within the lists by ids python?

I am getting data like this. Deposits from lists in this data should not be in other lists. How can I filter this list like this. Incoming data does not always have a specific index, number of deposits or withdrawals.
fakeData = [
{
'withId': 1232131212312, 'withAmount': 500,
'deposits': [{'id': 12321312312, 'type': 'deposit', 'amount': 250, 'date': '15-05-22 - 17:00:00'}, {'id': 123213123112, 'type': 'deposit', 'amount': 500, 'date': '15-05-22 - 00:00:00'}]},
{
'withId': 12326571312312, 'withAmount': 130, 'deposits': [{'id': 12321312312, 'type': 'deposit', 'amount': 250, 'date': '15-05-22 - 17:00:00'}, {'id': 123213123112, 'type': 'deposit', 'amount': 500, 'date': '15-05-22 - 00:00:00'}]},
{
'withId': 12321356712312, 'withAmount': 120,
'deposits': [{'id': 123213123112, 'type': 'deposit', 'amount': 500, 'date': '15-05-22 - 00:00:00'}]
}
]
Try this
def filter_packet(packet: list):
def filter_deposits(deposits: list, stack: list):
# Remove already-seen deposit IDs
result = list(filter(lambda x: x['id'] not in stack, deposits))
# Add the IDs to a stack
stack.extend([deposit['id'] for deposit in result])
return result
stack = []
filteredData = []
for packet in fakeData:
# Filter the deposits
new_deposits = filter_deposits(packet['deposits'], stack)
packet['deposits'] = new_deposits
filteredData.append(packet)
return filteredData

How to assign list values to dictionary keys?

categories = {'player_name': None, 'player_id': None, 'season': None}
L = ['Player 1', 'player_1', '2020']
How can I iterate over list and assign its values to the corresponding keys? so it would become something like:
{'player_name': 'Player 1', 'player_id': 'player_1, 'season': '2020'}
thanks
If python >= 3.6, then use zip() + dict(), if < 3.6, looks dict is un-ordered, so I don't know.
test.py:
categories = {'player_name': None, 'player_id': None, 'season': None}
L = ['Player 1', 'player_1', '2020']
print(dict(zip(categories, L)))
Results:
$ python3 test.py
{'player_name': 'Player 1', 'player_id': 'player_1', 'season': '2020'}
If the list has items in the same order as dictionary has keys i-e if player_name is the first element in the list then 'player_name' in the dictionary should come at first place
categories = {'player_name': None, 'player_id': None, 'season': None}
L = ['Player 1', 'player_1', '2020']
for key, value in zip(categories.keys(), L):
categories[key] = value
You could try something like this
categories = {'name':None, 'id':None, 'season':None}
L = ['Player 1', 'player_1', '2020']
it = iter(L)
for x in it:
categories['name'] = x
categories['id'] = next(it)
categories['season'] = next(it)
cat = { 'player_name' : None, 'player_id ': None, 'season' : None }
L = ['Player 1', 'player_1', 2020]
j = 0
for i in cat.keys():
cat[i] = L[j]
j += 1
This should solve your problem

assign a value of dictionary's key into a variable

I have the following code in Python:
def buildXmlUpdate(dfrom, roomId, ldays):
start_date_sard.text = dfrom
roomId = str(roomId)
room_id_sard.text = roomId
ldays = {'avail': str(), 'price': str()}
availability_in_data.text = ldays['avail']
price_in_data.text = ldays['price']
for n in ldays:
print (dfrom, roomId, ldays)
Now when running
buildXmlUpdate ('21/12/2015', 1, [{'avail': 1, 'price': 100}, {'avail': 3, 'price': 120}])
I get the following output
('21/12/2015', '1', {'avail': '', 'price': ''})
('21/12/2015', '1', {'avail': '', 'price': ''})
In other words:
('21/12/2015', '1', {'avail': 1, 'price': 100})
('21/12/2015', '1', {'avail': 3, 'price': 120})
As you see here, the dictionary avail and price keys are set to an empty string but I want to set them according to the ldays arguments in the method.
What am I doing wrong?
Solved:
def buildXmlUpdate(dfrom, roomId, ldays):
start_date_sard.text = dfrom
roomId = str(roomId)
room_id_sard.text = roomId
#ldays = {'avail': str(), 'price': str()}
#availability_in_data.text = ldays['avail']
#price_in_data.text = ldays['price']
for n in ldays:
print (dfrom, roomId, n)
#availability_in_data.text = get.ldays['avail']
#price_in_data.txt = get.ldays['price']
ldays[-1]['avail'] = str(ldays[-1]['avail'])
ldays[-1]['price'] =str(ldays[-1]['price'])
availability_in_data.text = ldays[-1]['avail']
price_in_data.text = ldays[-1]['price']
Thank you all!

Categories