Reputation: 41
I'm reading the contents of a JSON text file and am struggling to get the contents of a specific index in the data.
An example of the data objects I'm reading is below. There are multiple instances in my file, but they all look similar to the following:
[{ "value": "hello", "name": "janedoe", "istrue": "yes", "number": 5 }]
The console returns nothing every time and I can print json_list[0]
and it returns the whole value {'name': 'janedoe', 'number': 5}
.
I would like to use the substring "doe" to search within the list and find a match and then return the index of that match.
I have tried using a function and one liners such as this
res = [i for i in json_list if substring in i]
with open ('text.txt', 'r') as output_file:
json_array = json.load(output_file)
json_list = []
json_list = [{'name': item['name'].split('.')[0], 'number': item['number']}
for item in json_array]
substring = 'doe'
def index_containing_substring(json_list, substring):
for i, s in enumerate(json_list):
if substring in s:
return i
return -1
I would like to return the index value so that I can then call that index and utilize its data.
Upvotes: 1
Views: 83
Reputation: 2408
I would just go with a simple loop...
def find_doe_in_list_of_dicts(list_of_dicts):
for item in list_of_dicts:
if "doe" in item["name"]:
index_of_item_with_doe = list_of_dicts.index(item)
break
return index_of_item_with_joe
Or in a really ugly oneliner:
def find_doe_in_list_of_dicts(list_of_dicts):
return list_of_dicts.index([item for item in list_of_dicts if "name" in item and "doe" in item["name"]][0])
Upvotes: 1
Reputation: 353
Are we agree that you talk about dictionaries inside a list ? If I understand, you want to have an index to access like this:
tab = [{ "value": "hello", "name": "janedoe", "istrue": "yes", "number": 5 }]
% Doesn't work
print(tab[0][0]) // You would like "hello"
However, if you know that you just want "value", "name" or whatever, you can access like this:
tab = [{ "value": "hello", "name": "janedoe", "istrue": "yes", "number": 5 }]
# Display "hello"
print(tab[0]["value"])
You can use a loop like you did and get fields that you want. Is it what you want ?
EDIT:
This is the new code for what you want:
def index_containing_substring(list_dic, substring):
for i, s in enumerate(json_list):
for key in s:
if substring in s[key]:
# If you don't want the value remove s[key]
return i, key, s[key]
return -1
json_list = [
{ "value": "hello", "name": "janedoe", "istrue": "yes", "number": 5 },
{ "value": "hello", "name": "pop", "istrue": "yes", "number": 5 }
]
substring = 'doe'
# display: (0, 'name', 'janedoe')
print(index_containing_substring(json_list, substring))
I've modified a bit, but the function return the index of the table, and which key contains 'doe'. Notice in the code, that you just return the first element where you find 'doe' and not all elements. But it's not difficult to generalize if you want to have all result.
Upvotes: 2