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

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)

Related

Editing Dictionary in Python Not Working in Function [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 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

Sort list of dictionaries by key [duplicate]

This question already has answers here:
How do I sort a dictionary by key?
(32 answers)
Apply function to each element of a list
(4 answers)
Closed 5 months ago.
I have a list of dictionaries where the order of the keys is not consistent. Ideally I would like 'vid' to always come first with 'name' being second. As you can see below, sometimes 'name' comes first. How can I sort this list of dictionaries to always have 'vid' first?
viri_assets = [
{'vid': 'transpower_036', 'name': '221_02_PB_520_REF_174050'},
{'name': '242_07_DINA_HSTLR_YT_210238', 'vid': 'transpower_168'},
{'vid': 'transpower_170', 'name': '242_08_DINA_HSTLR_YT_210220'},
{'name': '251_PS04_PB_520_REF_109968', 'vid': 'transpower_166'},
{'vid': 'transpower_165', 'name': '251_PS05_PB_520_REF_109967'},
{'name': '31089', 'vid': 'transpower_064'}]
I have tried using sorted(viri_assets, key=lambda d: list(d.keys())) but it does not work.
You don't want to call sorted on your list, but on each dict of the list
Use .items() to get key-value pairs for each dict, and it'll sort them by the first element of the pair: the key. Set reverse to True to get "vid" before "name".
viri_assets = [{'vid': 'transpower_036', 'name': '221_02_PB_520_REF_174050'},
{'vid': 'transpower_065', 'name': '222_05_KAL_T2E_YT_344991'},
{'name': '226_02_INTL_PRSTR_ET_499802', 'vid': 'transpower_156'}]
viri_assets = [dict(sorted(d.items(), reverse=True)) for d in viri_assets]
print(viri_assets)
Output:
[{'vid': 'transpower_036', 'name': '221_02_PB_520_REF_174050'},
{'vid': 'transpower_065', 'name': '222_05_KAL_T2E_YT_344991'},
{'vid': 'transpower_156', 'name': '226_02_INTL_PRSTR_ET_499802'}]

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 prevent a for loop from overwriting a dictionary? [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 3 years ago.
Improve this question
I am creating a dictionary for a JSON file, through the use of a for loop.
However my for loop overwrites the entries
second_dict={}
third_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
for i in range(len(name)):
second_dict["hobbies"]=hobbies[i]
second_dict["age"]=age[i]
third_dict[name[i]]=second_dict
print(third_dict)
I am getting this output
{'suzen': {'hobbies': 'chess', 'age': 13},
'lilly': {'hobbies': 'chess', 'age': 13},
'sara': {'hobbies': 'chess', 'age': 13}}
Instead of getting this one
{'suzen': {'hobbies': 'chess', 'age': 13},
'lilly': {'hobbies': 'reading', 'age': 14},
'sara': {'hobbies': 'dancing', 'age': 15}}
can anyone please point out my mistake?
thank you
new_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
x = zip(name, hobbies, age)
for n,h,a in x:
new_dict[n]={'hobbies': h, 'age': a}
print(new_dict)
third_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
for i in range(len(name)):
second_dict={}
second_dict["hobbies"]=hobbies[i]
second_dict["age"]=age[i]
third_dict[name[i]]=second_dict
print(third_dict)
As pointed in comments, you should create a new object for each second_dict, there are 3 second_dict.

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