how to prevent a for loop from overwriting a dictionary? [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 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.

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

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)

Iterate through a list of dictionaries in python [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 2 years ago.
Improve this question
I am trying append a 'gameID' to a list if the game has been finished. I have a list of dictionaries called 'games_2020' that looks like
(ex. [ {'seasonYear': '2020', 'league': 'standard', 'gameID': '8133', 'statusGame': 'Finished', 'vTeam': LA}, {'seasonYear': '2020', 'league': 'standard', 'gameID': '8134', 'statusGame': 'Finished', 'vTeam': LA}.....]
My current code is below. 'gameID_finished' is where I want the 'gameID' for finished games to end up. games_2020 is what I want to iterate through. I am then trying to map through the entire list but I am running into an output of all the same 'gameID'
def check_finish(games):
if games_2020['statusGame'] == 'Finished':
gameID_finished.append(games_2020['gameID'])
else:
print('Scheduled')
You need to traverse each item in list to append to output. Please try the below code.
gameID_finished = []
games = [ {'seasonYear': '2020', 'league': 'standard', 'gameID': '8133', 'statusGame': 'Finished', 'vTeam': 'LA'}, {'seasonYear': '2020', 'league': 'standard', 'gameID': '8134', 'statusGame': 'Finished', 'vTeam': 'LA'}]
for games_2020 in games:
if games_2020['statusGame'] == 'Finished':
gameID_finished.append(games_2020['gameID'])
else:
print('Scheduled')

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.

Python extracting multiple values from the same key [duplicate]

This question already has an answer here:
Get a list of values from a list of dictionaries?
(1 answer)
Closed 8 years ago.
So I am bit new to Python. I am dealing with a problem I want to call the key ['name'] and get the following result:
['Tom', 'Mark' 'Pam']
However i seem to be in a little trouble due to multiple dictionaries in a list as seen in the code bellow.
people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
Thanks in advance!
You can use a list comprehension :
>>> [i['name'] for i in people if 'name' in i]
['Tom', 'Mark', 'Pam']

Categories

Resources