Extracting dictionary items embedded in a list
You can use list comprehension:
t = [{'a': 1.0, 'b': 2.0},
{'a': 3.0, 'b': 4.0},
{'a': 5.0, 'b': 6.0},
{'a': 7.0, 'b': 9.0},
{'a': 9.0, 'b': 0.0}]
new_list = [i["a"] for i in t]
Output:
[1.0, 3.0, 5.0, 7.0, 9.0]
Since this solution uses a for-loop, you can use map
instead:
x = list(map(lambda x: x["a"], t))
Output:
[1.0, 3.0, 5.0, 7.0, 9.0]
Performance-wise, you prefer to use list-comprehension solution rather the map one.
>>> timeit('new_list = [i["a"] for i in t]', setup='from __main__ import t', number=10000000)
4.318223718035199
>>> timeit('x = list(map(lambda x: x["a"], t))', setup='from __main__ import t', number=10000000)
16.243124993163093
def temp(p):
return p['a']
>>> timeit('x = list(map(temp, t))', setup='from __main__ import t, temp', number=10000000)
16.048683850689343
There is a slightly difference when using a lambda or a regular function; however, the comprehension execution takes 1/4 of the time.
How to extract value from dict inside list in python
NOTE: For adding the total
, read till the end
Firstly, to get a value of a certain value in a dict, the indexing is as follows
dict["key"]
and not dict.["key"]
Secondly, to append something to a list use parenthesis not square brackets. So,.append(x)
not .append[x]
Fixing these two things we have as of now:
dictlist = { "g1" : [], "g2" : [] , "g3" : [] }
a = ["a", 23]
a1 = ["asd", 3]
a2 = ["asdf", 10]
a3 = ["adg", 5]
b1 = ["df", 5]
b2 = ["dfg", 1]
c = ["dfg", 50]
dictlist["g1"].append(a)
dictlist["g1"].append(a1)
dictlist["g1"].append(a2)
dictlist["g1"].append(a3)
dictlist["g2"].append(b1)
dictlist["g2"].append(b2)
dictlist["g3"].append(c)
#Now, you want to print the key of the dict as the heading, so our first loop will be:
for heading in dict.keys(): # dictlist.keys() returns a list of all the keys
print(heading)
#The next thing you want is to print the values of the respective key seperated by ",":
for value in dict[heading]:
print(*value, sep=",") # we can use the sep keyword to print it as we require
# The at the end, an empty print() to seperate the headings
print()
Output:
g1
a, 23
asd, 3
asdf, 10
adg, 5
g2
df, 5
dfg, 1
g3
dfg, 50
Now, for adding the total
:
for heading in dict.keys():
print(heading)
total = 0 # We make a variable, becomes zero for every heading
for value in dict[heading]: # value is a list like ["a", 23], has str and int.. So;
total += sum(item for item in value if type(item) == int)
print(*value, sep=",")
#print the total before starting the next heading
print("total," total)
print()
Output:
g1
a, 23
asd, 3
asdf, 10
adg, 5
total, 41
g2
df, 5
dfg, 1
total, 6
g3
dfg, 50
total, 50
Python extract values of a key from a list of lists of dictionaries
You can do this with a list comprehension:
pValues = [[d["p"] for d in row] for row in data]
This iterates through each row of your list of lists of dictionaries, then iterates through each dictionary in the row and gets the value of "p" for each of them. (Note data
is your list of lists of dictionary)
How to extract data from a list of dictionaries from a filter
You can write a function and use filter(...)
on the list:
lst = [{'title': 'aaa', 'responses': '1 response', 'url': 'https://www.example.com/aaa'}, {'title': 'bbb', 'responses': '4 responses', 'url': 'https://www.example.com/bbb'}, {'title': 'ccc', 'responses': '2 responses', 'url': 'https://www.example.com/ccc'}, {'title': 'ddd', 'responses': '8 responses', 'url': 'https://www.example.com/ccc'}, {'title': 'eee', 'responses': '2 responses', 'url': 'https://www.example.com/eee'}]
def few_responses(item):
number, _ = item['responses'].split()
if (int(number) < 2):
return True
else:
return False
for item in filter(few_responses, lst):
print(item["url"])
Alternatively you can use a list comprehension that does the same:
urls = [item["url"]
for item in lst
for number, _ in [item["responses"].split()]
if (int(number) < 2)]
print(urls)
How can I extract all values from a dictionary in Python?
If you only need the dictionary keys 1
, 2
, and 3
use: your_dict.keys()
.
If you only need the dictionary values -0.3246
, -0.9185
, and -3985
use: your_dict.values()
.
If you want both keys and values use: your_dict.items()
which returns a list of tuples [(key1, value1), (key2, value2), ...]
.
how can I extract values from this dictionary in Python?
Also, assuming your file has new line delimited dictionaries, using below code solved the issue:
import json
fo = open(r"C:\Users\Downloads\test.txt", "r")
for each_line in fo.readlines():
print(json.loads(json.loads(each_line)['message'])['first_name'])
print(json.loads(json.loads(each_line)['message'])['last_name'])
print(json.loads(json.loads(each_line)['message'])['id'])
print(json.loads(json.loads(each_line)['message'])['phone'])
Extracting data from dictionary with a list inside (with more dicts inside)
TRY:
import json
import pandas as pd
with open('<json_file_path_here>', 'r') as f:
d = json.loads(f.read())
df = pd.DataFrame(d['Country'])
OUTPUT:
Team color
0 1 blue
1 2 red
2 3 orange
How to Extract Values from Dictionaries and Create Lists From Them
That can be done with a couple of comprehensions like:
Code:
def get_values_as_tuple(dict_list, keys):
return [tuple(d[k] for k in keys) for d in dict_list]
How?
How does this work? This is a nested comprehension. Let's go from the inside out, and start with:
tuple(d[k] for k in keys)
This creates a tuple of all of the elements in d
that are specified via k
in keys
. So, that is nice, but what the heck are d
, k
and keys
?
keys
is passed to the function, and are the keys we will look for in our dicts.k
is the individual values inkeys
fromk in keys
.d
is the individual dicts indict_list
fromd in dict_list
.
The outer comprehension builds a list of the tuples discussed above:
[tuple(d[k] for k in keys) for d in dict_list]
Test Code:
dictionaries = [{'id': 1, 'name': 'test1', 'description': 'foo'},
{'id': 2, 'name': 'test2', 'description': 'bar'}]
def get_values_as_tuple(dict_list, keys):
return [tuple(d[k] for k in keys) for d in dict_list]
print(get_values_as_tuple(dictionaries, ('id', 'name', 'description')))
Results:
[(1, 'test1', 'foo'), (2, 'test2', 'bar')]
Extract values from dictionary to list in Python
Just do :
>>> out = []
>>> for ele in Reference['Data']:
out.append(ele['red'])
>>> out
=> ['WA-1a9asd4sdfdas', 'WA-150824979asd4', 'WA-1508249792364']
Or, a single liner using List comprehension
:
>>> [ ele['red'] for ele in Reference['Data'] ]
=> ['WA-1a9asd4sdfdas', 'WA-150824979asd4', 'WA-1508249792364']
Related Topics
Python Multiprocessing Pool Hangs At Join
Tensorflow:Attributeerror: 'Module' Object Has No Attribute 'Mul'
Collect_List by Preserving Order Based on Another Variable
Pandas Fill in Missing Date Within Each Group With Information in the Previous Row
Test If Dictionary Key Exists, Is Not None and Isn't Blank
Stripping Whitespaces from a List Inside the List of Tuples
How to Get a Random Value from Dictionary
Using Beautifulsoup to Extract Text from Div
Pip Install Not Working With Jenkins
Animate a Rotating 3D Graph in Matplotlib
If-Condition With Multiple Actions in Robot Framework
How to Print Colored Text to the Terminal
Missing 1 Required Positional Argument - Issue
Sqlalchemy, Prevent Duplicate Rows
Getting the Bounding Box of the Recognized Words Using Python-Tesseract
Key Error: None of [Int64Index...] Dtype='Int64] Are in the Columns