Python-solidity-parser failed to handle throw keyword - python
I tried to parse the following code using python-solidity-parser (https://github.com/ConsenSys/python-solidity-parser)
pragma solidity ^0.4.13;
contract someContract {
mapping(address => uint) balances;
function deposit() payable {
balances[msg.sender] += msg.value;
}
function withdrawOkayish(uint amount) {
if(balances[msg.sender] >= amount) {
balances[msg.sender] -= amount; if(!msg.sender.send(amount)) { throw; }
}
}
function withdrawBad2(uint amount) {
if(balances[msg.sender] >= amount) {
balances[msg.sender] -= amount;
if(!msg.sender.call.gas(2500000).value(amount)()) { throw; }
}
}
}
It produces the following output
{'children': [{'name': 'solidity',
'type': 'PragmaDirective',
'value': '^0.4.13'},
{'baseContracts': [],
'kind': 'contract',
'name': 'someContract',
'subNodes': [{'initialValue': None,
'type': 'StateVariableDeclaration',
'variables': [{'expression': None,
'isDeclaredConst': False,
'isIndexed': False,
'isStateVar': True,
'name': 'balances',
'type': 'VariableDeclaration',
'typeName': {'keyType': {'name': 'address',
'type': 'ElementaryTypeName'},
'type': 'Mapping',
'valueType': {'name': 'uint',
'type': 'ElementaryTypeName'}},
'visibility': 'default'}]},
{'body': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '+=',
'right': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'value',
'type': 'MemberAccess'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'deposit',
'parameters': {'parameters': [],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': 'payable',
'type': 'FunctionDefinition',
'visibility': 'default'},
{'body': {'statements': [{'FalseBody': None,
'TrueBody': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '-=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'},
{'FalseBody': None,
'TrueBody': {'statements': [';'],
'type': 'Block'},
'condition': {'isPrefix': True,
'operator': '!',
'subExpression': {'arguments': [{'name': 'amount',
'type': 'Identifier'}],
'expression': {'expression': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'memberName': 'send',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'type': 'UnaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'condition': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '>=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'withdrawOkayish',
'parameters': {'parameters': [{'isIndexed': False,
'isStateVar': False,
'name': 'amount',
'storageLocation': None,
'type': 'Parameter',
'typeName': {'name': 'uint',
'type': 'ElementaryTypeName'}}],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': None,
'type': 'FunctionDefinition',
'visibility': 'default'},
{'body': {'statements': [{'FalseBody': None,
'TrueBody': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '-=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'},
{'FalseBody': None,
'TrueBody': {'statements': [';'],
'type': 'Block'},
'condition': {'isPrefix': True,
'operator': '!',
'subExpression': {'arguments': [],
'expression': {'arguments': [{'name': 'amount',
'type': 'Identifier'}],
'expression': {'expression': {'arguments': [{'number': '2500000',
'subdenomination': None,
'type': 'NumberLiteral'}],
'expression': {'expression': {'expression': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'memberName': 'call',
'type': 'MemberAccess'},
'memberName': 'gas',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'memberName': 'value',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'names': [],
'type': 'FunctionCall'},
'type': 'UnaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'condition': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '>=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'withdrawBad2',
'parameters': {'parameters': [{'isIndexed': False,
'isStateVar': False,
'name': 'amount',
'storageLocation': None,
'type': 'Parameter',
'typeName': {'name': 'uint',
'type': 'ElementaryTypeName'}}],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': None,
'type': 'FunctionDefinition',
'visibility': 'default'}],
'type': 'ContractDefinition'}],
'type': 'SourceUnit'}
I have found that it does not handle the throw keyword. Both if case block contains only ';'.
I am not able to find a way to resolve this issue. Is there any way to resolve this issue.
Created issue here: https://github.com/ConsenSys/python-solidity-parser/issues/11
(Still... not a Python programmer)
This took quite a bit of hacking around on my part just to pick up modifications. (For example, on my system, scripts/antlr4.sh (BTW, docs say script/antlr4, so... off to a great start.) doesn't execute properly)
That said, in the solidity_antlr4 directory is a parser.py source file.
It is missing a visitThrowStatement method.
I added:
def visitThrowStatement(self,ctx):
return Node(ctx=ctx,
type='ThrowStatement')
amongst the other visits* defs.
After moving my code to the site-packages (told ya... not a Python program, and definitely hacking around here, so not the right way to accomplish effecting this change I'm sure)
My output from running python3 -m solidity_parser parse ./samples/so_example.sol > testParse.txt (where ./samples/so_example.sol is your sample input) is:
{'children': [{'name': 'solidity',
'type': 'PragmaDirective',
'value': '^0.4.13'},
{'baseContracts': [],
'kind': 'contract',
'name': 'someContract',
'subNodes': [{'initialValue': None,
'type': 'StateVariableDeclaration',
'variables': [{'expression': None,
'isDeclaredConst': False,
'isIndexed': False,
'isStateVar': True,
'name': 'balances',
'type': 'VariableDeclaration',
'typeName': {'keyType': {'name': 'address',
'type': 'ElementaryTypeName'},
'type': 'Mapping',
'valueType': {'name': 'uint',
'type': 'ElementaryTypeName'}},
'visibility': 'default'}]},
{'body': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '+=',
'right': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'value',
'type': 'MemberAccess'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'deposit',
'parameters': {'parameters': [],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': 'payable',
'type': 'FunctionDefinition',
'visibility': 'default'},
{'body': {'statements': [{'FalseBody': None,
'TrueBody': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '-=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'},
{'FalseBody': None,
'TrueBody': {'statements': [{'type': 'ThrowStatement'}],
'type': 'Block'},
'condition': {'isPrefix': True,
'operator': '!',
'subExpression': {'arguments': [{'name': 'amount',
'type': 'Identifier'}],
'expression': {'expression': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'memberName': 'send',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'type': 'UnaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'condition': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '>=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'withdrawOkayish',
'parameters': {'parameters': [{'isIndexed': False,
'isStateVar': False,
'name': 'amount',
'storageLocation': None,
'type': 'Parameter',
'typeName': {'name': 'uint',
'type': 'ElementaryTypeName'}}],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': None,
'type': 'FunctionDefinition',
'visibility': 'default'},
{'body': {'statements': [{'FalseBody': None,
'TrueBody': {'statements': [{'expression': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '-=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'ExpressionStatement'},
{'FalseBody': None,
'TrueBody': {'statements': [{'type': 'ThrowStatement'}],
'type': 'Block'},
'condition': {'isPrefix': True,
'operator': '!',
'subExpression': {'arguments': [],
'expression': {'arguments': [{'name': 'amount',
'type': 'Identifier'}],
'expression': {'expression': {'arguments': [{'number': '2500000',
'subdenomination': None,
'type': 'NumberLiteral'}],
'expression': {'expression': {'expression': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'memberName': 'call',
'type': 'MemberAccess'},
'memberName': 'gas',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'memberName': 'value',
'type': 'MemberAccess'},
'names': [],
'type': 'FunctionCall'},
'names': [],
'type': 'FunctionCall'},
'type': 'UnaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'condition': {'left': {'base': {'name': 'balances',
'type': 'Identifier'},
'index': {'expression': {'name': 'msg',
'type': 'Identifier'},
'memberName': 'sender',
'type': 'MemberAccess'},
'type': 'IndexAccess'},
'operator': '>=',
'right': {'name': 'amount',
'type': 'Identifier'},
'type': 'BinaryOperation'},
'type': 'IfStatement'}],
'type': 'Block'},
'isConstructor': False,
'modifiers': [],
'name': 'withdrawBad2',
'parameters': {'parameters': [{'isIndexed': False,
'isStateVar': False,
'name': 'amount',
'storageLocation': None,
'type': 'Parameter',
'typeName': {'name': 'uint',
'type': 'ElementaryTypeName'}}],
'type': 'ParameterList'},
'returnParameters': [],
'stateMutability': None,
'type': 'FunctionDefinition',
'visibility': 'default'}],
'type': 'ContractDefinition'}],
'type': 'SourceUnit'}
relevant excerpt example:
'TrueBody': {'statements': [{'type': 'ThrowStatement'}],
'type': 'Block'},
I don't even know if this is the right content, but it does demonstrate that the solution will be to rebuild with a visitThrowStatement implemented.
(It's absence, would make me suspect other visitor methods may also be missing.)
Related
drop a dictionary with nan value
I have the following dictionary: my_dict = {'fields': ['id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': nan, 'name': 'bbb', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}, {'id': nan, 'name': 'ddd', 'type': 'string'}], 'type': 'struct' } From this dictionary, I would like to drop the dictionary with the id value nan value and would like to get the following. my_updated_dict = {'fields': ['id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}], 'type': 'struct' } I was trying changing to data frame and dropping the id value with the nan value and changing to dictionary back but couldn't get the intended result. my_updated_dict = pd.DataFrame(my_dict ).dropna().to_dict('list')
I do not know why would you need pandas for that if u can simply do: my_dict["fields"] = [i for i in my_dict["fields"] if not np.isnan(i["id"])] ** UPDATE ** if you really do need for some reason to use pandas, you may try this constructiion: my_dict["fields"] = pd.Series(my_dict["fields"]).apply(pd.Series).dropna().to_dict(orient="records") though I do not see any advantages over simple list comprehension, except may be on big volume of information.
You can use update() to overwrite the value of the key, then you can try: my_dict.update({'fields':[x for x in my_dict['fields'] if np.nan not in x.values()]}) Returning: {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}], 'type': 'struct'}
Considering the dictionary json import numpy as np json = {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': np.nan, 'name': 'bbb', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}, {'id': np.nan, 'name': 'ddd', 'type': 'string'}], 'type': 'struct'} In order to remove the parts where id is np.nan, one can use a list comprehension with numpy.isnan as follows json['fields'] = [x for x in json['fields'] if not np.isnan(x['id'])] [Out]: {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}], 'type': 'struct'}
How to Transform data in a nested json?
I have the following data, and when I used json_flatten i was able to extract most of the data except for deliveryMethod.items and languages.items. I also tried to use pd.json_normalize(a, record_path= 'deliveryMethod.items') but it doesn't seem to be working. a = {'ID': '1', 'Name': 'ABC', 'Center': 'Center For Education', 'providerNameAr': 'ABC', 'city': {'id': 1, 'cityEn': 'LA', 'regionId': 0, 'region': None}, 'cityName': None, 'LevelNumber': 'ABCD', 'activityStartDate': '09/01/2020', 'activityEndDate': '09/02/2020', 'activityType': {'lookUpId': 2, 'lookUpEn': 'Course', 'code': None, 'parent': None, 'hasParent': False}, 'deliveryMethod': {'items': [{'lookUpId': 2, 'lookUpEn': 'online' 'code': None, 'parent': None, 'hasParent': False}]}, 'languages': {'items': [{'lookUpId': 1, 'lookUpEn': 'English', 'code': None, 'parent': None, 'hasParent': False}]}, 'activityCategory': {'lookUpId': 1, 'lookUpEn': 'Regular', 'code': None, 'parent': None, 'hasParent': False}, 'address': 'LA', 'phoneNumber': '-11111', 'emailAddress': 'ABCS#Gmail.com', 'isAllSpeciality': True, 'requestId': 23, 'parentActivityId': None, 'sppData': None}
Convert nested dictionary, list, and dictionary into a pandas data frame in python
So, I am trying to work with a rest API, and it is giving me the following data: {'sports': [{'id': '20', 'uid': 's:20', 'name': 'Football', 'slug': 'football', 'leagues': [{'id': '28', 'uid': 's:20~l:28', 'name': 'National Football League', 'abbreviation': 'NFL', 'shortName': 'NFL', 'slug': 'nfl', 'teams': [{'team': {'id': '22', 'uid': 's:20~l:28~t:22', 'slug': 'arizona-cardinals', 'location': 'Arizona', 'name': 'Cardinals', 'nickname': 'Cardinals', 'abbreviation': 'ARI', 'displayName': 'Arizona Cardinals', 'shortDisplayName': 'Cardinals', 'color': 'A40227', 'alternateColor': '000000', 'isActive': True, 'isAllStar': False, 'logos': [{'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/ari.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'default'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/ari.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/scoreboard/ari.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard'], 'lastUpdated': '2018-06-05T12:11Z'}, ... I'm just interested in the teams data. However, I try to slice the pie, I'm having trouble extracting the desired information into the dataframe properly. Here is my code: url = 'http://site.api.espn.com/apis/site/v2/sports/football/nfl/teams' r = requests.get(url) teams_json = r.json() nfl = [] for teams in teams_json.items(): for x in teams: for row in x: print(row['teams']) I keep getting errors. Any assistance is greatly appreciated.
I'd suggest looking into how to navigate lists and dictionaries in python (that's all that json files are). It's just a matter of knowing the path, or how to iterate through those. To get into a dataframe, pandas has a nice .json_normalize() method. I'm not sure what data you want exactly, as the root teams key data is also nested. So depending what you are after, you may need to do a little extra work to extract what you want. But this is the general dataframe for teams. import requests import pandas as pd url = 'http://site.api.espn.com/apis/site/v2/sports/football/nfl/teams' jsonData = requests.get(url).json() teams_json = jsonData['sports'][0]['leagues'][0]['teams'] df = pd.json_normalize(teams_json) Output: print(df.head().to_string()) team.id team.uid team.slug team.location team.name team.nickname team.abbreviation team.displayName team.shortDisplayName team.color team.alternateColor team.isActive team.isAllStar team.logos team.record.items team.links 0 22 s:20~l:28~t:22 arizona-cardinals Arizona Cardinals Cardinals ARI Arizona Cardinals Cardinals A40227 000000 True False [{'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/ari.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'default'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/ari.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/scoreboard/ari.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/scoreboard/ari.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}] [{'summary': '11-6', 'stats': [{'name': 'playoffSeed', 'value': 5.0}, {'name': 'wins', 'value': 11.0}, {'name': 'losses', 'value': 6.0}, {'name': 'winPercent', 'value': 0.6470588445663452}, {'name': 'gamesBehind', 'value': 0.0}, {'name': 'ties', 'value': 0.0}, {'name': 'OTWins', 'value': 0.0}, {'name': 'OTLosses', 'value': 0.0}, {'name': 'gamesPlayed', 'value': 17.0}, {'name': 'pointsFor', 'value': 449.0}, {'name': 'pointsAgainst', 'value': 366.0}, {'name': 'avgPointsFor', 'value': 26.41176414489746}, {'name': 'avgPointsAgainst', 'value': 21.52941131591797}, {'name': 'points', 'value': 2.5}, {'name': 'differential', 'value': 83.0}, {'name': 'streak', 'value': -1.0}, {'name': 'clincher', 'value': 0.0}, {'name': 'divisionWinPercent', 'value': 0.6666666865348816}, {'name': 'leagueWinPercent', 'value': 0.5833333134651184}, {'name': 'divisionRecord', 'value': 0.0}, {'name': 'divisionWins', 'value': 4.0}, {'name': 'divisionTies', 'value': 0.0}, {'name': 'divisionLosses', 'value': 2.0}]}] [{'language': 'en-US', 'rel': ['clubhouse', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/_/name/ari/arizona-cardinals', 'text': 'Clubhouse', 'shortText': 'Clubhouse', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['roster', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/roster/_/name/ari/arizona-cardinals', 'text': 'Roster', 'shortText': 'Roster', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['stats', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/stats/_/name/ari/arizona-cardinals', 'text': 'Statistics', 'shortText': 'Statistics', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['schedule', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/schedule/_/name/ari', 'text': 'Schedule', 'shortText': 'Schedule', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['photos', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/photos/_/name/ari', 'text': 'photos', 'shortText': 'photos', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['scores', 'sportscenter', 'app', 'team'], 'href': 'sportscenter://x-callback-url/showClubhouse?uid=s:20~l:28~t:22§ion=scores', 'text': 'Scores', 'shortText': 'Scores', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['draftpicks', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/draft/teams/_/name/ari/arizona-cardinals', 'text': 'Draft Picks', 'shortText': 'Draft Picks', 'isExternal': False, 'isPremium': True}, {'language': 'en-US', 'rel': ['transactions', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/transactions/_/name/ari', 'text': 'Transactions', 'shortText': 'Transactions', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['injuries', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/injuries/_/name/ari', 'text': 'Injuries', 'shortText': 'Injuries', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['depthchart', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/depth/_/name/ari', 'text': 'Depth Chart', 'shortText': 'Depth Chart', 'isExternal': False, 'isPremium': False}, {'language': 'en', 'rel': ['tickets', 'desktop', 'team'], 'href': 'https://www.vividseats.com/nfl-football/arizona-cardinals-tickets.html?wsUser=717', 'text': 'Tickets', 'isExternal': True, 'isPremium': False}] 1 1 s:20~l:28~t:1 atlanta-falcons Atlanta Falcons Falcons ATL Atlanta Falcons Falcons 000000 000000 True False [{'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/atl.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'default'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/atl.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/scoreboard/atl.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/scoreboard/atl.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}] [{'summary': '7-10', 'stats': [{'name': 'playoffSeed', 'value': 12.0}, {'name': 'wins', 'value': 7.0}, {'name': 'losses', 'value': 10.0}, {'name': 'winPercent', 'value': 0.4117647111415863}, {'name': 'gamesBehind', 'value': 0.0}, {'name': 'ties', 'value': 0.0}, {'name': 'OTWins', 'value': 0.0}, {'name': 'OTLosses', 'value': 0.0}, {'name': 'gamesPlayed', 'value': 17.0}, {'name': 'pointsFor', 'value': 313.0}, {'name': 'pointsAgainst', 'value': 459.0}, {'name': 'avgPointsFor', 'value': 18.41176414489746}, {'name': 'avgPointsAgainst', 'value': 27.0}, {'name': 'points', 'value': -1.5}, {'name': 'differential', 'value': -146.0}, {'name': 'streak', 'value': -2.0}, {'name': 'clincher', 'value': 0.0}, {'name': 'divisionWinPercent', 'value': 0.3333333432674408}, {'name': 'leagueWinPercent', 'value': 0.3333333432674408}, {'name': 'divisionRecord', 'value': 0.0}, {'name': 'divisionWins', 'value': 2.0}, {'name': 'divisionTies', 'value': 0.0}, {'name': 'divisionLosses', 'value': 4.0}]}] [{'language': 'en-US', 'rel': ['clubhouse', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/_/name/atl/atlanta-falcons', 'text': 'Clubhouse', 'shortText': 'Clubhouse', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['roster', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/roster/_/name/atl/atlanta-falcons', 'text': 'Roster', 'shortText': 'Roster', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['stats', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/stats/_/name/atl/atlanta-falcons', 'text': 'Statistics', 'shortText': 'Statistics', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['schedule', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/schedule/_/name/atl', 'text': 'Schedule', 'shortText': 'Schedule', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['photos', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/photos/_/name/atl', 'text': 'photos', 'shortText': 'photos', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['scores', 'sportscenter', 'app', 'team'], 'href': 'sportscenter://x-callback-url/showClubhouse?uid=s:20~l:28~t:1§ion=scores', 'text': 'Scores', 'shortText': 'Scores', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['draftpicks', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/draft/teams/_/name/atl/atlanta-falcons', 'text': 'Draft Picks', 'shortText': 'Draft Picks', 'isExternal': False, 'isPremium': True}, {'language': 'en-US', 'rel': ['transactions', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/transactions/_/name/atl', 'text': 'Transactions', 'shortText': 'Transactions', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['injuries', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/injuries/_/name/atl', 'text': 'Injuries', 'shortText': 'Injuries', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['depthchart', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/depth/_/name/atl', 'text': 'Depth Chart', 'shortText': 'Depth Chart', 'isExternal': False, 'isPremium': False}, {'language': 'en', 'rel': ['tickets', 'desktop', 'team'], 'href': 'https://www.vividseats.com/nfl-football/atlanta-falcons-tickets.html?wsUser=717', 'text': 'Tickets', 'isExternal': True, 'isPremium': False}] 2 2 s:20~l:28~t:2 buffalo-bills Buffalo Bills Bills BUF Buffalo Bills Bills 04407F c60c30 True False [{'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/buf.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'default'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/buf.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/scoreboard/buf.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/scoreboard/buf.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}] [{'summary': '11-6', 'stats': [{'name': 'playoffSeed', 'value': 3.0}, {'name': 'wins', 'value': 11.0}, {'name': 'losses', 'value': 6.0}, {'name': 'winPercent', 'value': 0.6470588445663452}, {'name': 'gamesBehind', 'value': 0.0}, {'name': 'ties', 'value': 0.0}, {'name': 'OTWins', 'value': 0.0}, {'name': 'OTLosses', 'value': 1.0}, {'name': 'gamesPlayed', 'value': 17.0}, {'name': 'pointsFor', 'value': 483.0}, {'name': 'pointsAgainst', 'value': 289.0}, {'name': 'avgPointsFor', 'value': 28.41176414489746}, {'name': 'avgPointsAgainst', 'value': 17.0}, {'name': 'points', 'value': 2.5}, {'name': 'differential', 'value': 194.0}, {'name': 'streak', 'value': 4.0}, {'name': 'clincher', 'value': 0.0}, {'name': 'divisionWinPercent', 'value': 0.8333333134651184}, {'name': 'leagueWinPercent', 'value': 0.5833333134651184}, {'name': 'divisionRecord', 'value': 0.0}, {'name': 'divisionWins', 'value': 5.0}, {'name': 'divisionTies', 'value': 0.0}, {'name': 'divisionLosses', 'value': 1.0}]}] [{'language': 'en-US', 'rel': ['clubhouse', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/_/name/buf/buffalo-bills', 'text': 'Clubhouse', 'shortText': 'Clubhouse', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['roster', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/roster/_/name/buf/buffalo-bills', 'text': 'Roster', 'shortText': 'Roster', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['stats', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/stats/_/name/buf/buffalo-bills', 'text': 'Statistics', 'shortText': 'Statistics', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['schedule', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/schedule/_/name/buf', 'text': 'Schedule', 'shortText': 'Schedule', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['photos', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/photos/_/name/buf', 'text': 'photos', 'shortText': 'photos', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['scores', 'sportscenter', 'app', 'team'], 'href': 'sportscenter://x-callback-url/showClubhouse?uid=s:20~l:28~t:2§ion=scores', 'text': 'Scores', 'shortText': 'Scores', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['draftpicks', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/draft/teams/_/name/buf/buffalo-bills', 'text': 'Draft Picks', 'shortText': 'Draft Picks', 'isExternal': False, 'isPremium': True}, {'language': 'en-US', 'rel': ['transactions', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/transactions/_/name/buf', 'text': 'Transactions', 'shortText': 'Transactions', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['injuries', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/injuries/_/name/buf', 'text': 'Injuries', 'shortText': 'Injuries', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['depthchart', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/depth/_/name/buf', 'text': 'Depth Chart', 'shortText': 'Depth Chart', 'isExternal': False, 'isPremium': False}, {'language': 'en', 'rel': ['tickets', 'desktop', 'team'], 'href': 'https://www.vividseats.com/nfl-football/buffalo-bills-tickets.html?wsUser=717', 'text': 'Tickets', 'isExternal': True, 'isPremium': False}] 3 3 s:20~l:28~t:3 chicago-bears Chicago Bears Bears CHI Chicago Bears Bears 152644 0b162a True False [{'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/chi.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'default'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/chi.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/scoreboard/chi.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/scoreboard/chi.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}] [{'summary': '6-11', 'stats': [{'name': 'playoffSeed', 'value': 13.0}, {'name': 'wins', 'value': 6.0}, {'name': 'losses', 'value': 11.0}, {'name': 'winPercent', 'value': 0.3529411852359772}, {'name': 'gamesBehind', 'value': 0.0}, {'name': 'ties', 'value': 0.0}, {'name': 'OTWins', 'value': 0.0}, {'name': 'OTLosses', 'value': 0.0}, {'name': 'gamesPlayed', 'value': 17.0}, {'name': 'pointsFor', 'value': 311.0}, {'name': 'pointsAgainst', 'value': 407.0}, {'name': 'avgPointsFor', 'value': 18.294116973876953}, {'name': 'avgPointsAgainst', 'value': 23.941177368164062}, {'name': 'points', 'value': -2.5}, {'name': 'differential', 'value': -96.0}, {'name': 'streak', 'value': -1.0}, {'name': 'clincher', 'value': 0.0}, {'name': 'divisionWinPercent', 'value': 0.3333333432674408}, {'name': 'leagueWinPercent', 'value': 0.3333333432674408}, {'name': 'divisionRecord', 'value': 0.0}, {'name': 'divisionWins', 'value': 2.0}, {'name': 'divisionTies', 'value': 0.0}, {'name': 'divisionLosses', 'value': 4.0}]}] [{'language': 'en-US', 'rel': ['clubhouse', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/_/name/chi/chicago-bears', 'text': 'Clubhouse', 'shortText': 'Clubhouse', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['roster', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/roster/_/name/chi/chicago-bears', 'text': 'Roster', 'shortText': 'Roster', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['stats', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/stats/_/name/chi/chicago-bears', 'text': 'Statistics', 'shortText': 'Statistics', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['schedule', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/schedule/_/name/chi', 'text': 'Schedule', 'shortText': 'Schedule', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['photos', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/photos/_/name/chi', 'text': 'photos', 'shortText': 'photos', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['scores', 'sportscenter', 'app', 'team'], 'href': 'sportscenter://x-callback-url/showClubhouse?uid=s:20~l:28~t:3§ion=scores', 'text': 'Scores', 'shortText': 'Scores', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['draftpicks', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/draft/teams/_/name/chi/chicago-bears', 'text': 'Draft Picks', 'shortText': 'Draft Picks', 'isExternal': False, 'isPremium': True}, {'language': 'en-US', 'rel': ['transactions', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/transactions/_/name/chi', 'text': 'Transactions', 'shortText': 'Transactions', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['injuries', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/injuries/_/name/chi', 'text': 'Injuries', 'shortText': 'Injuries', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['depthchart', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/depth/_/name/chi', 'text': 'Depth Chart', 'shortText': 'Depth Chart', 'isExternal': False, 'isPremium': False}, {'language': 'en', 'rel': ['tickets', 'desktop', 'team'], 'href': 'https://www.vividseats.com/nfl-football/chicago-bears-tickets.html?wsUser=717', 'text': 'Tickets', 'isExternal': True, 'isPremium': False}] 4 4 s:20~l:28~t:4 cincinnati-bengals Cincinnati Bengals Bengals CIN Cincinnati Bengals Bengals FF2700 000000 True False [{'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/cin.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'default'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/cin.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500/scoreboard/cin.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard'], 'lastUpdated': '2018-06-05T12:11Z'}, {'href': 'https://a.espncdn.com/i/teamlogos/nfl/500-dark/scoreboard/cin.png', 'width': 500, 'height': 500, 'alt': '', 'rel': ['full', 'scoreboard', 'dark'], 'lastUpdated': '2018-06-05T12:11Z'}] [{'summary': '10-7', 'stats': [{'name': 'playoffSeed', 'value': 4.0}, {'name': 'wins', 'value': 10.0}, {'name': 'losses', 'value': 7.0}, {'name': 'winPercent', 'value': 0.5882353186607361}, {'name': 'gamesBehind', 'value': 0.0}, {'name': 'ties', 'value': 0.0}, {'name': 'OTWins', 'value': 1.0}, {'name': 'OTLosses', 'value': 2.0}, {'name': 'gamesPlayed', 'value': 17.0}, {'name': 'pointsFor', 'value': 460.0}, {'name': 'pointsAgainst', 'value': 376.0}, {'name': 'avgPointsFor', 'value': 27.058822631835938}, {'name': 'avgPointsAgainst', 'value': 22.117647171020508}, {'name': 'points', 'value': 1.5}, {'name': 'differential', 'value': 84.0}, {'name': 'streak', 'value': -1.0}, {'name': 'clincher', 'value': 0.0}, {'name': 'divisionWinPercent', 'value': 0.6666666865348816}, {'name': 'leagueWinPercent', 'value': 0.6666666865348816}, {'name': 'divisionRecord', 'value': 0.0}, {'name': 'divisionWins', 'value': 4.0}, {'name': 'divisionTies', 'value': 0.0}, {'name': 'divisionLosses', 'value': 2.0}]}] [{'language': 'en-US', 'rel': ['clubhouse', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/_/name/cin/cincinnati-bengals', 'text': 'Clubhouse', 'shortText': 'Clubhouse', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['roster', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/roster/_/name/cin/cincinnati-bengals', 'text': 'Roster', 'shortText': 'Roster', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['stats', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/team/stats/_/name/cin/cincinnati-bengals', 'text': 'Statistics', 'shortText': 'Statistics', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['schedule', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/schedule/_/name/cin', 'text': 'Schedule', 'shortText': 'Schedule', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['photos', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/photos/_/name/cin', 'text': 'photos', 'shortText': 'photos', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['scores', 'sportscenter', 'app', 'team'], 'href': 'sportscenter://x-callback-url/showClubhouse?uid=s:20~l:28~t:4§ion=scores', 'text': 'Scores', 'shortText': 'Scores', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['draftpicks', 'desktop', 'team'], 'href': 'http://www.espn.com/nfl/draft/teams/_/name/cin/cincinnati-bengals', 'text': 'Draft Picks', 'shortText': 'Draft Picks', 'isExternal': False, 'isPremium': True}, {'language': 'en-US', 'rel': ['transactions', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/transactions/_/name/cin', 'text': 'Transactions', 'shortText': 'Transactions', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['injuries', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/injuries/_/name/cin', 'text': 'Injuries', 'shortText': 'Injuries', 'isExternal': False, 'isPremium': False}, {'language': 'en-US', 'rel': ['depthchart', 'desktop', 'team'], 'href': 'https://www.espn.com/nfl/team/depth/_/name/cin', 'text': 'Depth Chart', 'shortText': 'Depth Chart', 'isExternal': False, 'isPremium': False}, {'language': 'en', 'rel': ['tickets', 'desktop', 'team'], 'href': 'https://www.vividseats.com/nfl-football/cincinnati-bengals-tickets.html?wsUser=717', 'text': 'Tickets', 'isExternal': True, 'isPremium': False}] ... [25 rows x 16 columns]
json.items() returns not just the values but the keys also, meaning that the first value in teams is the string "sports" and the second value is what you are looking for, the list. That's what is causing the error. Edit: You want to do for key, teams in teams_json.items() not for teams in teams_json.items()
how do I check the complete array?
I am trying to check for the data-id is equal or not from the given list array how do I check the complete array to know where the id is found or not? order_id= 121553197332 inf = {data of array given below} if inf[n]["id"] == order_id: info = inf[n]["info"] elif do someting here return (info) the array in need to check? [{'amount': 0.3, 'id': '121553197332', 'info': {'avgFillPrice': None, 'id': '121553197332', 'ioc': False, 'liquidation': False, 'market': 'FTT/USD', 'postOnly': True, 'price': '40.0', 'reduceOnly': False, 'remainingSize': '0.3', 'side': 'buy', 'size': '0.3', 'status': 'open', 'type': 'limit'}, 'side': 'buy', 'status': 'open', 'stopPrice': None, 'symbol': 'FTT/USD', 'trades': [], 'type': 'limit'}, {'amount': 0.3, 'id': '121553197726', 'info': {'avgFillPrice': None, 'future': None, 'id': '121553197726', 'ioc': False, 'liquidation': False, 'market': 'FTT/USD', 'postOnly': True, 'price': '40.062', 'side': 'buy', 'size': '0.3', 'status': 'open', 'type': 'limit'}, 'postOnly': True, 'price': 40.062, 'remaining': 0.3, 'side': 'buy', 'status': 'open', 'stopPrice': None, 'symbol': 'FTT/USD', 'trades': [], 'type': 'limit'}] I need to return the info of the array at last.
You Can try use a for loop like this: inf = [{ 'amount': 0.3, 'id': '121553197332', 'info': { 'avgFillPrice': None, 'id': '121553197332', 'ioc': False, 'liquidation': False, 'market': 'FTT/USD', 'postOnly': True, 'price': '40.0', 'reduceOnly': False, 'remainingSize': '0.3', 'side': 'buy', 'size': '0.3', 'status': 'open', 'type': 'limit' }, 'side': 'buy', 'status': 'open', 'stopPrice': None, 'symbol': 'FTT/USD', 'trades': [], 'type': 'limit' }, { 'amount': 0.3, 'id': '121553197726', 'info': { 'avgFillPrice': None, 'future': None, 'id': '121553197726', 'ioc': False, 'liquidation': False, 'market': 'FTT/USD', 'postOnly': True, 'price': '40.062', 'side': 'buy', 'size': '0.3', 'status': 'open', 'type': 'limit' }, 'postOnly': True, 'price': 40.062, 'remaining': 0.3, 'side': 'buy', 'status': 'open', 'stopPrice': None, 'symbol': 'FTT/USD', 'trades': [], 'type': 'limit' }] order_id= 121553197332 for inner_data in inf: if inner_data['id'] == order_id: print(inner_data) info = inner_data["info"]
Use next: # Sample data (reduced) orders = [{ 'id': '121553197332', 'info': { 'id': '121553197332' }, }, { 'id': '121553197726', 'info': { 'id': '121553197726' }, }] # The order to find order_id = 121553197332 # Find it found = next((d for d in orders if int(d["id"]) == order_id), None)
Here is the snippet that is ready to run. target variable is the one you are searching for in the records. data = [{'amount': 0.3, 'id': '121553197332', 'info': {'avgFillPrice': None, 'id': '121553197332', 'ioc': False, 'liquidation': False, 'market': 'FTT/USD', 'postOnly': True, 'price': '40.0', 'reduceOnly': False, 'remainingSize': '0.3', 'side': 'buy', 'size': '0.3', 'status': 'open', 'type': 'limit'}, 'side': 'buy', 'status': 'open', 'stopPrice': None, 'symbol': 'FTT/USD', 'trades': [], 'type': 'limit'}, {'amount': 0.3, 'id': '121553197726', 'info': {'avgFillPrice': None, 'future': None, 'id': '121553197726', 'ioc': False, 'liquidation': False, 'market': 'FTT/USD', 'postOnly': True, 'price': '40.062', 'side': 'buy', 'size': '0.3', 'status': 'open', 'type': 'limit'}, 'postOnly': True, 'price': 40.062, 'remaining': 0.3, 'side': 'buy', 'status': 'open', 'stopPrice': None, 'symbol': 'FTT/USD', 'trades': [], 'type': 'limit'}] target= '121553197726' for d in data: if d['id']==target: info = d["info"] print(info) else: pass
How to extract elements from nested dict
1.I need to get the value for business' name and append it to a list. 2.I need to get the value policies and append to a list after checking parent. 3.if parent is Marketing name has to added to level1. 4.if parent is Advertising name has to added to level2. 5.if some place Business is [] I need to pass None instead of Null List Also need to check key exists or not for some keys there is a chance of missing policies, business Sample dictionary is below searchtest = [{'_index': 'newtest', '_type': '_doc', '_id': '100', '_score': 1.0, '_source': {'id': '100', 'name': 'A', 'Business': [{'id': '7', 'name': 'Enterprise'}, {'id': '8', 'name': 'Customer'}], 'policies': [{'id': '332', 'name': 'Second division', 'parent': 'Marketing'}, {'id': '3323', 'name': 'First division', 'parent': 'Marketing'}]}}, {'_index': 'newtest', '_type': '_doc', '_id': '101', '_score': 1.0, '_source': {'id': '101', 'name': 'B', 'Business': [{'id': '7'}, {'id': '8', 'name': 'Customer'}], 'policies': [{'id': '332', 'name': 'Second division', 'parent': 'Marketing'}, {'id': '3323', 'name': 'First division', 'parent': 'Marketing'}]}}] Expected out [ { "id": "100", "name": "A", "Business": ["Enterprise", "Customer"], "level1": ['Second division', 'First division'], "level2": [ ] }, { "id": "101", "name": "B", "Business": ["Enterprise", "Customer"], "level1": ['Second division', 'First division'], "level2": [ ] } ] COde is below def do_the_thing(lst): resp = [] parents_mapper = { 'Marketing': 'level1', 'Advertising': 'level2' } for el in lst: d = { 'id': el['_source']['id'], 'name': el['_source']['name'], 'Business': [], 'level1': [], 'level2': [] } for business in el.get("_source", {}).get("business", {}).get("name", ""): business_name = business.get('name') if business_name: d['Business'].append(business_name) for policy in el.get('policies', []): policy_parent = policy.get('parent') parent_found = parents_mapper.get(policy_parent) policy_name = policy.get('name') if parent_found and policy_name: d[parent_found].append(policy_name) resp.append(d) return resp if __name__ == "__main__": import pprint pp = pprint.PrettyPrinter(4) pp.pprint(do_the_thing(searchtest)) My output [ {'Business': [], 'id': '100', 'level1': [], 'level2': [], 'name': 'A'}, {'Business': [], 'id': '101', 'level1': [], 'level2': [], 'name': 'B'}] The problem in my output you can see: 'Business', 'level1' is [] is null list. Adding one more dictionary for testing searchtest = [{'_index': 'newtest', '_type': '_doc', '_id': '100', '_score': 1.0, '_source': {'id': '100', 'name': 'A', 'policies': [{'id': '332', 'name': 'Second division', 'parent': 'Marketing'}, {'id': '3323', 'name': 'First division', 'parent': 'Marketing'}]}}, {'_index': 'newtest', '_type': '_doc', '_id': '101', '_score': 1.0, '_source': {'id': '101', 'name': 'B', 'Business': [{'id': '9'}, {'id': '10', 'name': 'Customer'}], 'policies': [{'id': '332', 'name': 'Second division', 'parent': 'Marketing'}, {'id': '3323', 'name': 'First division', 'parent': 'Advertising'}]}}] In the above dictionary you can see that there is no Business in 100 key and for 101 there is no name inside the Business key. So there will be key error will be coming. Need to handle that
You are not collecting data from dict, You have to select particular key to get it's value. replace this : for el in lst: d = { 'id': el['_source']['id'], 'name': el['_source']['name'], 'Business': [], 'level1': [], 'level2': [] } with this: for el in data: d = { 'id' : el['_source']['id'], 'name' : el['_source']['name'], 'Business' : [name['name'] for name in el['_source']['Business']], 'level1' : [name['name'] for name in el['_source']['policies']], 'level2' : [] } output: [ { 'Business': ['Enterprise', 'Customer'], 'id': '100', 'level1': ['Second division', 'First division'], 'level2': [], 'name': 'A'}, { 'Business': ['Enterprise', 'Customer'], 'id': '101', 'level1': ['Second division', 'First division'], 'level2': [], 'name': 'B'}]