Editing Dictionary in Python Not Working in Function [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 days ago.
Improve this question
I'm trying to edit a dictionary. My logic works without the use of a function, but once I add a function to the mix, it doesn't.
The results of the following code are what I desire.
thDic = {
'123': {
'type': 'Web Map'
},
'456': {
'type': 'Web Mapping Application'
}
}
for k,v in thDic.items():
v['type'] = 'asdf'
thDic
{'123': {'type': 'asdf'}, '456': {'type': 'asdf'}}
However, when I put the for loop into a function, it stops giving me the desired results.
def test(thDic):
for k,v in thDic.items():
v['type'] = 'asdf'
return thDic
thDic
{'123': {'type': 'Web Map'}, '456': {'type': 'Web Mapping Application'}}

You did not call the function
def test(thDic):
for k,v in thDic.items():
v['type'] = 'asdf'
return thDic
thDic = test(thDic)
thDic

Related

In my List of multiple dictionaries only my last dictionary item save on database, I want to save all [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I would like to save each dictionary as a separate instance of a db model using sqlalchemy.
I tried
from models.ordermodels import OrderModel, OrderItemsModel
for dic in request.cartItems:
order_item_a = OrderItemsModel(
name=dic.name,
quantity=dic.quantity,
price=dic.price,
order_id=x,
)
db.add(order_item_a)
in output
"cartItems": [
{
"name": "string",
"quantity": 0,
"price": 0
},
{
"name": "string",
"quantity": 110,
"price": 0
}
]
It only saves the last item , I want to save all the item in database. I'm using Postgresql
I'm pretty sure that only the last item is saved because you only save the last item.
You probably wrote something like this:
from models.ordermodels import OrderModel, OrderItemsModel
for dic in request.cartItems:
order_item_a = OrderItemsModel(
name=dic.name,
quantity=dic.quantity,
price=dic.price,
order_id=x,
)
db.add(order_item_a)
when in fact you should have written this:
from models.ordermodels import OrderModel, OrderItemsModel
for dic in request.cartItems:
order_item_a = OrderItemsModel(
name=dic.name,
quantity=dic.quantity,
price=dic.price,
order_id=x,
)
db.add(order_item_a)

How to convert dict containing tuple values to string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
How to convert the following Input to the desired output using python.
Input:
{'Id': (34,), 'user': ('a.t#gmail.com',), 'createdOn': ('12 Oct',), 'status': (False,), 'message': ('Hello',)}
Output:
{'Id': 34, 'user': 'a.t#gmail.com', 'createdOn':'12 Oct', 'status': False, 'message': 'Hello'}
Just take first index for each value :
your_dict = {'Id': (34,), 'user': ('a.t#gmail.com',), 'createdOn': ('12 Oct',), 'status': (False,), 'message': ('Hello',)}
your_dict = {key:val[0] for key, val in your_dict.items()}
Why are the values in a tuple to begin with?
old_dict = {'Id': (34,), 'user': ('a.t#gmail.com',), 'createdOn': ('12 Oct',), 'status': (False,), 'message': ('Hello',)}
new_dict = {k:v[0] for k,v in old_dict.items()}
print(new_dict)

If dictionary value exists multiple times in list of dicts, delete specific dict from list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a function that returns a list of dictionaries like this:
[{'Status': 'Deleted', 'Name': "My First Test"}, {'Status': 'Modified', 'Name': "My First Test"}]
As you can see, "My First Test" is in there twice. Normally this wouldn't be an issue, however, based on what I know about what's happening on the back-end, the only dict that I actually want is the "Modified" dict.
Essentially, I'm looking for a way to say "if dict['Status'] == 'Modified' and dict['Status'] == 'Deleted' for the same Name, delete the one with the 'Deleted' status."
I don't know if I understood well your question.
But it's a tip:
list = [
{
'Status': 'Deleted',
'Name': "My First Test"
},
{
'Status': 'Modified',
'Name': "My First Test"
}]
filterd_list = [l for l in list if l['Status'] == 'Modified']
print(filterd_list) # Only the modified one will be printed

Python: TypeError: string indices must be integers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
This is a similar problem posted here lots of time but I am unable to get my head around it.
import json
str2 ="""[{'cta': [], 'ctr': 2880509, 'client_id': '229132', 'exchange': 'NSE_EQ', 'token': '3063', 'product': 'CO', 'order_type': 'M', 'duration': 'DAY', 'price': '0', 'trigger_price': '149.10', 'quantity': 1, 'disclosed_quantity': 0, 'side': 'S', 'avg_price': '148.10', 'traded_quantity': 1, 'pending_quantity': 0, 'message': '', 'exchange_order_id': '1300000006005800', 'syom_order_id': 'NA', 'order_number': '191101000336718', 'timestamp': '01/11/2019,12:19:45', 'exchange_timestamp': '01-Nov-2019 12:19:45', 'status': 'complete', 'time_in_micro': '1572590985928000', 'is_amo': False, 'order_complexity': 'CO', 'request_id': '1', 'valid_date': '--', 'tag': 'JWEB|TB1', 'comments': 'PLACE ORDER :: 229132|NSE_EQ|3063|EQ|I|0|1|S|CO|WEB|IP-172-31-4-125|1572590985897', 'fill_id': '', 'original_message': '', '_amo': False}]"""
str2 = (json.dumps(str2))
print(str2)
print(str2['client_id'])
Why this doesn't work? It says -
print(str2['client_id'])
TypeError: string indices must be integers
Note that str2 is output from someplace and my goal is to fetch the client_id or any other variable.
So what I am seeking is what is the possible way to parse it?
There are mutliple problems here. You don't seem to be thinking this through.
You start with a string. Calling json.dumps on a string just gives you another string. But you couldn't have called json.loads on the original string either, because it is not JSON; it appears to be a string representation of a Python object.
But then, even if you had correctly parsed it, it still wouldn't work, because it represents a list of dictionaries, not a single dict.
It seems unlikely that this is actually the output from your external system. If you want further help, you will need to explain exactly how you got that string.

How to build array from json input file in python 3? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to build an array from the information comming from a local json file.
The desired output array format is:
output = [
'elementa-element2-element3',
'elementa-element2-element3',
]
The input from json is:
import json
with open('/Users/user/test.json', 'r') as f:
array = json.load(f)
print (array)
{'responseHeader': {'zkConnected': True, 'status': 0, 'QTime': 2, 'params': {'q': 'facet_gender:man', 'start': '0', 'fq': 'lang:de', 'rows': '10000', 'wt': 'json', 'facet': 'true'}}, 'response': {'numFound': 1005, 'start': 0, 'docs': [
{'rmc': 'm228238-0042', 'title': 'Day-Date 40', 'family': 'Day-Date', 'familyCode': 'day-date', 'facet_case_title': ['Oyster, 40 mm, Gelbgold']},
{'rmc': 'm326935-0007', 'title': 'Sky-Dweller', 'family': 'Sky-Dweller', 'familyCode': 'sky-dweller', 'facet_case_title': ['Oyster, 42 mm, Everose-Gold']}, ...
How can I acess the rows and build my array from all rows?
output = array
while i < len(array)
output[i] = array['response']['docs'][i]['familyCode']+'/'+array['response']['docs'][i]['rmc']
The json.load() will return a dictionary. This dictionary can be nested, if the json file contains nested elements. This is the case in your example, too.
If you format your json a little bit, it will be more clear:
{
'responseHeader': {
'zkConnected': True,
'status': 0,
'QTime': 2,
'params': {
'q': 'facet_gender:man',
'start': '0',
'fq': 'lang:de',
'rows': '10000',
'wt': 'json',
'facet':
'true'
}
},
'response': {
'numFound': 1005,
'start': 0,
'docs': [
{'rmc': 'm228238-0042', 'title': 'Day-Date 40', 'family': 'Day-Date', 'familyCode': 'day-date', 'facet_case_title': ['Oyster, 40 mm, Gelbgold']},
{'rmc': 'm326935-0007', 'title': 'Sky-Dweller', 'family': 'Sky-Dweller', 'familyCode': 'sky-dweller', 'facet_case_title': ['Oyster, 42 mm, Everose-Gold']},
...
]
}
}
If you want to retrieve the "docs", you actually need this:
array["response"]["docs"]
In your example, it is a list, and it can be used as you would normally do.
Example 1: get the first element of the list
documents = array["response"]["docs"] # Create new variable "documents".
print(documents[0]) # Print out first element of "docs" variable.
Example 2: Iterate over every element:
documents = array["response"]["docs"]
for document in documents:
print(document)

Categories

Resources