I have two dictionaries - basic dictionary and additional, and I want to use additional dictionary data to interact with function and append data to the 1st one.
dict_report = {'Id': p_id, 'First name': person_name, 'Age': p_age} #basic dict
iter_params = {'Shape': 0, 'Margin': 1} #additional
I have a function which accepts 3 arguments and I want to use 2nd dict value as 1st argument.
Let's say, in basic language:
def function():
shape = concatvals(iter_params_mammo(['Shape'],14,19)) #goes to cell value directly
margin = concatvals(iter_params_mammo(['Margin'], 14, 19))
dict_report.add(shape,margin)
return dict_report
Should return
dict_report = {'Id': p_id, 'First name': person_name, 'Age': p_age, 'Shape': "specific shape", 'Margin': "specific margin"}
Can I somehow not specify shape and margin, but just append new values to dict automatically, depending on additional dictionary size and values, but use their values to create new data?
Not sure if this is what you wanted but here is a rough copy.
toda will pull a value from existing dict based on the key passed in.
arba reinserts the key.
shimi will update become the existing dict then update to add new key value pair
dict_report = {'Id': 'p_id', 'First name': 'person_name', 'Age': 'p_age'}
kv = iter_params = {'Shape': 0, 'Margin': 1}
toda = iter_params.get('Shape')
arba = {'Shape': toda}
print(arba)
def dict_merge(x):
shimi = dict_report
shimi.update(x)
print(shimi)
return shimi
dict_merge(arba)
I am not sure what function you want to create or parameters, but as far as I can tell you just want to merge a dictionary and return it otherwise, so, here's that:
dict_report = {'Id': "p_id", 'First name': "person_name", 'Age': "p_age"} #basic dict
iter_params = {'Shape': 0, 'Margin': 1}
def func(d1,d2,arg3):
for k,v in d2.items():
#perform function on v
#e.g. v += 1 or whatever you want
#add to dict_report
d1[k] = v
return d1
dict_report = func(dict_report,iter_params,"3rd parameter?")
print (dict_report)
prints:
{'Id': 'p_id', 'Shape': 0, 'First name': 'person_name', 'Margin': 1, 'Age': 'p_age'}
Related
I have a problem. I have a dict my_Dict. This is somewhat nested. However, I would like to 'clean up' the dict my_Dict, by this I mean that I would like to separate all nested ones and also generate a unique ID so that I can later find the corresponding object again.
For example, I have detail: {...}, this nested, should later map an independent dict my_Detail_Dict and in addition, detail should receive a unique ID within my_Dict. Unfortunately, my list that I give out is empty. How can I remove my slaughtered keys and give them an ID?
my_Dict = {
'_key': '1',
'group': 'test',
'data': {},
'type': '',
'code': '007',
'conType': '1',
'flag': None,
'createdAt': '2021',
'currency': 'EUR',
'detail': {
'selector': {
'number': '12312',
'isTrue': True,
'requirements': [{
'type': 'customer',
'requirement': '1'}]
}
}
}
def nested_dict(my_Dict):
my_new_dict_list = []
for key in my_Dict.keys():
#print(f"Looking for {key}")
if isinstance(my_Dict[key], dict):
print(f"{key} is nested")
# Add id to nested stuff
my_Dict[key]["__id"] = 1
my_nested_Dict = my_Dict[key]
# Delete all nested from the key
del my_Dict[key]
# Add id to key, but not the nested stuff
my_Dict[key] = 1
my_new_dict_list.append(my_Dict[key])
my_new_dict_list.append(my_Dict)
return my_new_dict_list
nested_dict(my_Dict)
[OUT] []
# What I want
[my_Dict, my_Details_Dict, my_Data_Dict]
What I have
{'_key': '1',
'group': 'test',
'data': {},
'type': '',
'code': '007',
'conType': '1',
'flag': None,
'createdAt': '2021',
'currency': 'EUR',
'detail': {'selector': {'number': '12312',
'isTrue': True,
'requirements': [{'type': 'customer', 'requirement': '1'}]}}}
What I want
my_Dict = {'_key': '1',
'group': 'test',
'data': 18,
'type': '',
'code': '007',
'conType': '1',
'flag': None,
'createdAt': '2021',
'currency': 'EUR',
'detail': 22}
my_Data_Dict = {'__id': 18}
my_Detail_Dict = {'selector': {'number': '12312',
'isTrue': True,
'requirements': [{'type': 'customer', 'requirement': '1'}]}, '__id': 22}
The following code snippet will solve what you are trying to do:
my_Dict = {
'_key': '1',
'group': 'test',
'data': {},
'type': '',
'code': '007',
'conType': '1',
'flag': None,
'createdAt': '2021',
'currency': 'EUR',
'detail': {
'selector': {
'number': '12312',
'isTrue': True,
'requirements': [{
'type': 'customer',
'requirement': '1'}]
}
}
}
def nested_dict(my_Dict):
# Initializing a dictionary that will store all the nested dictionaries
my_new_dict = {}
idx = 0
for key in my_Dict.keys():
# Checking which keys are nested i.e are dictionaries
if isinstance(my_Dict[key], dict):
# Generating ID
idx += 1
# Adding generated ID as another key
my_Dict[key]["__id"] = idx
# Adding nested key with the ID to the new dictionary
my_new_dict[key] = my_Dict[key]
# Replacing nested key value with the generated ID
my_Dict[key] = idx
# Returning new dictionary containing all nested dictionaries with ID
return my_new_dict
result = nested_dict(my_Dict)
print(my_Dict)
# Iterating through dictionary to get all nested dictionaries
for item in result.items():
print(item)
If I understand you correctly, you wish to automatically make each nested dictionary it's own variable, and remove it from the main dictionary.
Finding the nested dictionaries and removing them from the main dictionary is not so difficult. However, automatically assigning them to a variable is not recommended for various reasons. Instead, what I would do is store all these dictionaries in a list, and then assign them manually to a variable.
# Prepare a list to store data in
inidividual_dicts = []
id_index = 1
for key in my_Dict.keys():
# For each key, we get the current value
value = my_Dict[key]
# Determine if the current value is a dictionary. If so, then it's a nested dict
if isinstance(value, dict):
print(key + " is a nested dict")
# Get the nested dictionary, and replace it with the ID
dict_value = my_Dict[key]
my_Dict[key] = id_index
# Add the id to previously nested dictionary
dict_value['__id'] = id_index
id_index = id_index + 1 # increase for next nested dic
inidividual_dicts.append(dict_value) # store it as a new dictionary
# Manually write out variables names, and assign the nested dictionaries to it.
[my_Details_Dict, my_Data_Dict] = inidividual_dicts
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 API response for listing out information of all Volumes. I want to loop through the response and get the value of the name and assign each one of them dynamically to each url.
This is my main API endpoint which returns the following:
[{'source': None, 'serial': '23432', 'created': '2018-11-
12T04:27:14Z', 'name': 'v001', 'size':
456456}, {'source': None, 'serial': '4364576',
'created': '2018-11-12T04:27:16Z', 'name': 'v002',
'size': 345435}, {'source': None, 'serial':
'6445645', 'created': '2018-11-12T04:27:17Z', 'name': 'v003', 'size':
23432}, {'source': None,
'serial': 'we43235', 'created': '2018-11-12T04:27:20Z',
'name': 'v004', 'size': 35435}]
I'm doing this to get the value of 'name'
test_url = 'https://0.0.0.0/api/1.1/volume'
test_data = json.loads(r.get(test_url, headers=headers,
verify=False).content.decode('UTF-8'))
new_data = [{
'name': value['name']
} for value in test_data]
final_data = [val['name'] for val in new_data]
for k in final_data:
print(k)
k prints out all the values in name, but i'm stuck at where i want to be able to use it in assigning different API endpoints. Now, k returns
v001
v002
v003
v004
I want to assign each one of them to different endpoints like below:
url_v001 = test_url + v001
url_v002 = test_url + v002
url_v003 = test_url + v003
url_v004 = test_url + v004
I want this to be dynamically done, because there may be more than 4 volume names returned by my main API.
It wouldn't be good to do that, but the best way is to use a dictionary:
d={}
for k in final_test:
d['url_'+k] = test_url + k
Or much better in a dictionary comprehension:
d={'url_'+k:test_url + k for k in final_test}
And now:
print(d)
Both reproduce:
{'url_v001': 'https://0.0.0.0/api/1.1/volumev001', 'url_v002': 'https://0.0.0.0/api/1.1/volumev002', 'url_v003': 'https://0.0.0.0/api/1.1/volumev003', 'url_v004': 'https://0.0.0.0/api/1.1/volumev004'}
To use d:
for k,v in d.items():
print(k+',',v)
Outputs:
url_v001, https://0.0.0.0/api/1.1/volumev001
url_v002, https://0.0.0.0/api/1.1/volumev002
url_v003, https://0.0.0.0/api/1.1/volumev003
url_v004, https://0.0.0.0/api/1.1/volumev004
I have a list of dictionaries in python and I would like to override old value with duplicate value. Please let me know how can I do.
{'message': [{'name': 'raghav', 'id': 10}, {'name': 'raghav', 'id': 11}]}
Output should be:
{'message': [ {'name': 'raghav', 'id': 11}]}
I don't know what you mean by "override old value with duplicate value". If you mean just picking the second dict from the list, you could:
print({k: [v[1]] for (k, v) in data.items()})
If the idea is to update the "name" with a newer value of "id" as you move along the list, then maybe:
def merge_records(data):
records = data['message']
users = {}
for record in records:
name = record['name']
id_ = record['id']
users[name] = id_
new_records = []
for name, id_ in users.items():
new_records.append({'name': name, 'id': id_})
return {'message': new_records}
But, if you have any control over how the data is represented, you might reconsider. You probably want a different data structure.
Here you go:
d = {'message': [{'name': 'raghav', 'id': 10}, {'name': 'raghav', 'id': 11}]}
#loop over outer dictionary
for key, value in d.items():
d[key] = [dict([t for k in value for t in k.items()])]
print(d)
Edit:
As per your requirement:
d = {'message': [ {'name': 'raghav', 'id': 11}, {'name': 'krish', 'id': 20}, {'name': 'anu', 'id': 30}]}
for key, value in d.items():
print [dict((k1,v1)) for k1,v1 in dict([tuple(i.items()) for i in value for val in i.items()]).items()]
I have an error with this line. I am working with a dictionary from a file with an import. This is the dictionary:
users = [{'id':1010,'name':"Administrator",'type':1},{'id':1011,'name':"Administrator2",'type':1}]
And the method with which the work is as follows:
def addData(dict, entry):
new = {}
x = 0
for i in dict.keys():
new[i] = entry(x)
x += 1
dict.append(new)
Where "dict" would be "users", but the error is that the dictionary does not recognize me as such. Can anyone tell me, I have wrong in the dictionary?
That's not a dicionary, it's a list of dictionaries!
EDIT: And to make this a little more answer-ish:
users = [{'id':1010,'name':"Administrator",'type':1},{'id':1011,'name':"Administrator2",'type':1}]
newusers = dict()
for ud in users:
newusers[ud.pop('id')] = ud
print newusers
#{1010: {'type': 1, 'name': 'Administrator'}, 1011: {'type': 1, 'name': 'Administrator2'}}
newusers[1012] = {'name': 'John', 'type': 2}
print newusers
#{1010: {'type': 1, 'name': 'Administrator'}, 1011: {'type': 1, 'name': 'Administrator2'}, 1012: {'type': 2, 'name': 'John'}}
Which is essentially the same as dawgs answer, but with a simplified approach on generating the new dictionary
Perhaps you are looking to do something along these lines:
users = [{'id':1010,'name':"Administrator",'type':1},{'id':1011,'name':"Administrator2",'type':1}]
new_dict={}
for di in users:
new_dict[di['id']]={}
for k in di.keys():
if k =='id': continue
new_dict[di['id']][k]=di[k]
print new_dict
# {1010: {'type': 1, 'name': 'Administrator'}, 1011: {'type': 1, 'name': 'Administrator2'}}
Then you can do:
>>> new_dict[1010]
{'type': 1, 'name': 'Administrator'}
Essentially, this is turning a list of anonymous dicts into a dict of dicts that are keys from the key 'id'