3

In such an example:

"[{'id' : 18, 'name' : 'Rick'}, {'id' : 19, 'name' : 'Luke'}]"

I am working with a str representation of a list of dicts. How can I iterate through the list to return a new list of all the "id's" in the dictionaries?

The desired result:

[18, 19]

EDIT: I have tried already to cast the string into a list with ast.literal_eval(foolist) and iterated through the items in the list. However, when I do this, it iterates through the characters in foolist starting with "{" then "'".

aritroper
  • 1,671
  • 5
  • 16
  • 26

6 Answers6

2

As suggested in several comments:

import ast


foolist = "[{'id' : 18, 'name' : 'Rick'}, {'id' : 19, 'name' : 'Luke'}]"
[d["id"] for d in ast.literal_eval(foolist)]
# [18, 19]
pylang
  • 40,867
  • 14
  • 129
  • 121
0

I guess this code would serve your purpose

a = "[{'id' : 18, 'name' : 'Rick'}, {'id' : 19, 'name' : 'Luke'}]"

a = a.split(',')
output = []
for data in a:
    data = data.replace('[', '').replace('{','').replace(']','').replace('}','').replace(' ','')
    if eval(data.split(':')[0]) == 'id':
        output.append(data.split(':')[1])
print(output)
Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
0

I have adapted a previous answer on Combining 2 dictionaries with common key.

def mergeDoLs(*dicts):
    def flatten(LoL):
        return [e for l in LoL for e in l]
    rtr= {k: [] for k in set(flatten(d for d in dicts))}
    for k, v in flatten(d.items() for d in dicts):
        rtr[k].append(v)
    return rtr

d_str = "[{'id' : 18, 'name' : 'Rick'}, {'id' : 19, 'name' : 'Luke'}]"
d = mergeDoLs(*eval(d_str))
d['id']

# output
# d = {'id': [18, 19], 'name': ['Rick', 'Luke']}
# d['id'] = [18, 19]
jpp
  • 159,742
  • 34
  • 281
  • 339
0

Use JSON built-in library.

import json

raw_string = "[{'id' : 18, 'name' : 'Rick'}, {'id' : 19, 'name' : 'Luke'}]"
json_string = raw_string.replace('\'', '"') #converting NON-JSON string to JSON string


my_dictionary = dict()
my_dictionary = json.loads(json_string)

ids = []

for item in my_dictionary:
    ids.append(int(item['id']))

print(ids)
Eziz Durdyyev
  • 1,110
  • 2
  • 16
  • 34
0

I tried this:-

import json

a = "[{'id' : 18, 'name' : 'Rick'}, {'id' : 19, 'name' : 'Luke'}]"
final_list = []
a = a.replace("'",'"')
b = '{"chck":'+a+"}"
b = json.loads(b)
for i in b.values():
    for j in i:
        final_list.append(j['id'])
print (final_list)
Narendra
  • 1,511
  • 1
  • 10
  • 20
0

Just try this method :

import ast

data="[{'id' : 18, 'name' : 'Rick'}, {'id' : 19, 'name' : 'Luke'}]"


print(list(map(lambda x:x['id'],ast.literal_eval(data))))

output:

[18, 19]