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
Related
I am new to Python. I am trying to create a new list based on a specific condition, which is fruits['type'] === 'edit'.
fruits = [{'type': 'edit',
'ns': 0,
'title': 'List',
'pageid': 39338740},
{'type': 'new',
'ns': 0,
'title': 'John Braid',
'pageid': 8164456},
{'type': 'edit',
'ns': 0,
'title': 'lokan',
'pageid': 65869267}]
My code returns an empty array:
newlist = []
for x in fruits:
if x['type'] == 'edit' in x:
newlist.append(x)
print(newlist)
fruits = [{'type': 'edit',
'ns': 0,
'title': 'List',
'pageid': 39338740},
{'type': 'new',
'ns': 0,
'title': 'John Braid',
'pageid': 8164456},
{'type': 'edit',
'ns': 0,
'title': 'lokan',
'pageid': 65869267}]
newlist = [fruit for fruit in fruits if fruit["type"] == "edit"]
print(newlist)
You can create new list with list comprehension,
new_list = [d for d in fruits if d['type'] == 'edit']
Which is equal to,
new_list = []
for d in fruits:
if d['type'] == 'edit':
new_list.append(d)
for x in fruits:
try:
if x['type'] == 'edit':
newlist.append(x)
except:
pass
print(newlist)
Your code didn't work, as you included in x in your if statement, which was already answered. But I wanted to include further explanation, which hopefully will be helpful.
x['type'] == 'edit' evaluates to True or False which means that your code:
if x['type'] == 'edit' in x
actually looks like that when you intended it to append to the list:
if True in x
And True is, of course, not an element of x, so this is False, so your list never is appended.
there are list :
data = ['man', 'man1', 'man2']
key = ['name', 'id', 'sal']
man_res = ['Alexandra', 'RST01', '$34,000']
man1_res = ['Santio', 'RST009', '$45,000']
man2_res = ['Rumbalski', 'RST50', '$78,000']
the expected output will be nested output:
Expected o/p:- {'man':{'name':'Alexandra', 'id':'RST01', 'sal':$34,000},
'man1':{'name':'Santio', 'id':'RST009', 'sal':$45,000},
'man2':{'name':'Rumbalski', 'id':'RST50', 'sal':$78,000}}
Easy way would be using pandas dataframe
import pandas as pd
df = pd.DataFrame([man_res, man1_res, man2_res], index=data, columns=key)
print(df)
df.to_dict(orient='index')
name id sal
man Alexandra RST01 $34,000
man1 Santio RST009 $45,000
man2 Rumbalski RST50 $78,000
{'man': {'name': 'Alexandra', 'id': 'RST01', 'sal': '$34,000'},
'man1': {'name': 'Santio', 'id': 'RST009', 'sal': '$45,000'},
'man2': {'name': 'Rumbalski', 'id': 'RST50', 'sal': '$78,000'}}
Or you could manually merge them using dict + zip
d = dict(zip(
data,
(dict(zip(key, res)) for res in (man_res, man1_res, man2_res))
))
d
{'man': {'name': 'Alexandra', 'id': 'RST01', 'sal': '$34,000'},
'man1': {'name': 'Santio', 'id': 'RST009', 'sal': '$45,000'},
'man2': {'name': 'Rumbalski', 'id': 'RST50', 'sal': '$78,000'}}
#save it in 2D array
all_man_res = []
all_man_res.append(man_res)
all_man_res.append(man1_res)
all_man_res.append(man2_res)
print(all_man_res)
#Add it into a dict output
output = {}
for i in range(len(l)):
person = l[i]
details = {}
for j in range(len(key)):
value = key[j]
details[value] = all_man_res[i][j]
output[person] = details
output
The pandas dataframe answer provided by NoThInG makes the most intuitive sense. If you are looking to use only the built in python tools, you can do
info_list = [dict(zip(key,man) for man in (man_res, man1_res, man2_res)]
output = dict(zip(data,info_list))
I have a list of dictionaries but I want to store 3 values from a dictionary named 'price'
My code is
response = yf.Ticker("FB").stats()["price"]
output:
{'averageDailyVolume10Day': 19621971,
'averageDailyVolume3Month': 16023089,
'circulatingSupply': None,
'currency': 'USD',
'currencySymbol': '$',
'exchange': 'NMS',
'exchangeDataDelayedBy': 0,
'exchangeName': 'NasdaqGS',
'fromCurrency': None,
'lastMarket': None,
'longName': 'Facebook, Inc.',
'marketCap': 960766541824,
'marketState': 'REGULAR',
'maxAge': 1,
'openInterest': None,
'postMarketChange': None,
'postMarketPrice': None,
'preMarketChange': 3.51001,
'preMarketChangePercent': 0.0103239,
'preMarketPrice': 343.5,
'preMarketSource': 'FREE_REALTIME',
'preMarketTime': 1634736599,
'priceHint': 2,
'quoteSourceName': 'Nasdaq Real Time Price',
'quoteType': 'EQUITY',
'regularMarketChange': 0.7750244,
'regularMarketChangePercent': 0.0022795508,
'regularMarketDayHigh': 343.94,
'regularMarketDayLow': 339.7,
'regularMarketOpen': 343.445,
'regularMarketPreviousClose': 339.99,
'regularMarketPrice': 340.765,
'regularMarketSource': 'FREE_REALTIME',
'regularMarketTime': 1634749118,
'regularMarketVolume': 8538416,
'shortName': 'Facebook, Inc.',
'strikePrice': None,
'symbol': 'FB',
'toCurrency': None,
'underlyingSymbol': None,
'volume24Hr': None,
'volumeAllCurrencies': None}
I would like to get only shortName, regularMarketPrice and symbol
I know that if I want to exctrat one value I should run
response = yf.Ticker("FB").stats()["price"]["shortName"]
but is there a way to store all 3 values in response?
Assuming the output dictionary you show is stored in response variable, you can try this -
keys = ['shortName', 'regularMarketPrice', 'symbol']
filtered_response = {k:response.get(k) for k in keys}
{'shortName': 'Facebook, Inc.',
'regularMarketPrice': 340.765,
'symbol': 'FB'}
#RJ has it right in the comments, but here some explanation for you:
In this case, yf.Ticker("FB").stats()["price"]["shortName"] is returning you the entire dictionary. So all of values are being returned and stored in response.
So you can just do:
response = yf.Ticker("FB").stats()["price"]
shortName = response["shortName"]
regularMarketPrice = response["regularMarketPrice"]
symbol = response["symbol"]
d = {...}
market_price, name, symbol = [d.get(k) for k in d if k == "regularMarketPrice" or k == "shortName" or k == "symbol"]
print(f'MarketPrice: {market_price}')
print(f'shortName : {name}')
print(f'symbol : {symbol}')
I have an SQL database that I need to fetch and convert to JSON. I am thinking that the first step to do that is to fetch the data from the database and load it as a dataframe, then convert the dataframe into JSON object.
Let's say I have the following dataframe.
df_school = pd.DataFrame({'id':[1,2,3,4], 'school_code': ['ABC', 'IJK', 'QRS', 'XYZ'], 'name': ['School A','School B', 'School C', 'School D'], 'type':['private', 'public', 'public', 'private']})
print(df_school)
I want to convert it to JSON with the following code.
import collections
object_list =[]
for idx, row in df_school.iterrows():
d = collections.OrderedDict()
d['id'] = row['id']
d['school_code'] = row['school_code']
d['name'] = row['name']
d['type'] = row['type']
object_list.append(d)
j = json.dumps(object_list)
object_list = 'school_objects.js'
f = open(object_list, 'w')
print(j)
But the result is string. It only looks like a JSON, but when I try to access the item inside the so-called JSON, like j[0] it prints [, not an item inside the JSON.
I also tried another approach, by converting the result from SQL directly to JSON.
query = "Select * from school;"
df_school = pd.read_sql_query(query, connection)
json_school = df_school.head(10).to_json(orient='records')
But I also still got string.
How do I convert it to real JSON object?
Given the provided df_school variable, we can just do j=df_school.to_json(orient='records') to turn it into a JSON formatted string.
Once we have j storing the JSON formatted string, if we want to do something with it, we first have to load the JSON into Python again using json.loads(j).
So if we do:
j = df_school.to_json(orient='records')
# parse j into Python
loaded_json = json.loads(j)
print(loaded_json[0])
# print outputs: {'id': 1, 'name': 'School A', 'school_code': 'ABC', 'type': 'private'}
Hope this helps!
import pandas as pd
import json
df_school = pd.DataFrame({'id':[1,2,3,4], 'school_code': ['ABC', 'IJK', 'QRS', 'XYZ'], 'name': ['School A','School B', 'School C', 'School D'], 'type':['private', 'public', 'public', 'private']})
str_school = df_school.to_json(orient='records')
json_school = json.loads(str_school)
json_school[0]
{'id': 1, 'school_code': 'ABC', 'name': 'School A', 'type': 'private'}
JSON is a string encoding of objects.
Once you use json.dumps() or similar, you'll get a string.
Try the below code, Hope this will help :
data = [{columns:df_school.iloc[i][columns] for columns in list(df_school.columns) } for i in range(df_school.shape[0]) ]
print(data)
print("***********************")
print(type(data[0]))
Ouput will be :
[{'id': 1, 'school_code': 'ABC', 'name': 'School A', 'type': 'private'},
{'id': 2, 'school_code': 'IJK', 'name': 'School B', 'type': 'public'},
{'id': 3, 'school_code': 'QRS', 'name': 'School C', 'type': 'public'},
{'id': 4, 'school_code': 'XYZ', 'name': 'School D', 'type': 'private'}]
*************************
<class 'dict'>
data={k:list(v.values()) for k,v in df_school.to_dict().items()}
{
'id': [1, 2, 3, 4],
'school_code': ['ABC', 'IJK', 'QRS', 'XYZ'],
'name': ['School A', 'School B', 'School C', 'School D'],
'type': ['private', 'public', 'public', 'private']
}
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}]