I have a Json array which has key value pairs. I want to get value of a particular key in the list. I don't know at what position the key will be in the array so I cant use the index in the array.
How can I get this please? I have tried something like below code to get value of 'filterB' which is 'val1' but no luck. Thanks.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
w = y['filters']['filterB']
print (w)
w = y['filters']['filterB'] doesn't work because y['filters'] is a list and not dict.
The answer to your question depends on how you want to handle the case of multiple dictionaries inside filters list that have filterB key.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
# all filterB values
filter_b_values = [x['filterB'] for x in y['filters'] if 'filterB' in x.keys()]
# take first filterB value or None if no values
w = filter_b_values[0] if filter_b_values else None
The source of your data (json) has nothing to do with what you want, which is to find the dictionary in y['filters'] that contains a key called filterB. To do this, you need to iterate over the list and look for the item that fulfils this condition.
w = None
for item in y['filters']:
if 'filterB' in item:
w = item['filterB']
break
print(w) # val1
Alternatively, you could join all dictionaries into a single dictionary and use that like you originally tried
all_dict = dict()
for item in y['filters']:
all_dict.update(item)
# Replace the list of dicts with the dict
y['filters'] = all_dict
w = y['filters']['filterB']
print(w) # val1
If you have multiple dictionaries in the list that fulfil this condition and you want w to be a list of all these values, you could do:
y = {"filters":[{"filterA":"All"},{"filterB":"val1"},{"filterB":"val2"}]}
all_w = list()
for item in y['filters']:
if 'filterB' in item:
all_w.append(item['filterB'])
Or, as a list-comprehension:
all_w = [item['filterB'] for item in y['filters'] if 'filterB' in item]
print(all_w) # ['val1', 'val2']
Note that a list comprehension is just syntactic sugar for an iteration that creates a list. You aren't avoiding any looping by writing a regular loop as a list comprehension
Related
dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
"""code here"""
For the above code I need to get the output as :
a
b
c
I know if we put print(i), we will get the desired output, but the answer expected is in terms of K.
Actual answer is: print(k[0]),which I am unable to understand.
Thanks
Since you define values of dictionary equal to a tuple here:
dictionary[my_list[i]] = (my_list[i],)
k is a tuple which means for it to print the actual value you need to get the first item in k by using the following:
dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
print(k[0])
Output:
a
b
c
k[0] just gets the first item in the tuple ('a',). This makes it print a instead of ('a',).
I have a dictionary where the values are a list of tuples.
dictionary = {1:[('hello, how are you'),('how is the weather'),('okay
then')], 2:[('is this okay'),('maybe It is')]}
I want to make the values a single string for each key. So I made a function which does the job, but I do not know how to get insert it back to the original dictionary.
my function:
def list_of_tuples_to_string(dictionary):
for tup in dictionary.values():
k = [''.join(i) for i in tup] #joining list of tuples to make a list of strings
l = [''.join(k)] #joining list of strings to make a string
for j in l:
ki = j.lower() #converting string to lower case
return ki
output i want:
dictionary = {1:'hello, how are you how is the weather okay then', 2:'is this okay maybe it is'}
You can simply overwrite the values for each key in the dictionary:
for key, value in dictionary.items():
dictionary[key] = ' '.join(value)
Note the space in the join statement, which joins each string in the list with a space.
It can be done even simpler than you think, just using comprehension dicts
>>> dictionary = {1:[('hello, how are you'),('how is the weather'),('okay then')],
2:[('is this okay'),('maybe It is')]}
>>> dictionary = {key:' '.join(val).lower() for key, val in dictionary.items()}
>>> print(dictionary)
{1: 'hello, how are you how is the weather okay then', 2: 'is this okay maybe It is'}
Now, let's go through the method
we loop through the keys and values in the dictionary with dict.items()
assign the key as itself together with the value as a string consisting of each element in the list.
The elemts are joined together with a single space and set to lowercase.
Try:
for i in dictionary.keys():
dictionary[i]=' '.join(updt_key.lower() for updt_key in dictionary[i])
In python 3, I am trying to create an array of elements, where each element consists of two values. These values are not really key-value pairs because they are equally related to each other, meaning value 1 could be the key for value two, just as value two could be the key to value one and so I didn't think a dictionary was appropriate.
my_list = [ (VALUE1, OFFSET1), (VALUE2, OFFSET2) ]
def printList(list):
for item in list:
print(item)
How could I collect the VALUE and OFFSET "values" separately? Such as
theValue = list[0].VALUE
theOffset = list[0].OFFSET
I'm thinking an array of structs perhaps?
You can use zip, which transposes the list and collects elements at the same position to one element in the result:
value, offset = zip(*my_list)
value
#('VALUE1', 'VALUE2')
offset
#('OFFSET1', 'OFFSET2')
def printList(my_list):
for item in my_list:
print('Value ', item[0])
print('Offset ', item[1])
The for loop iterates through my_list. Each element in the loop is received as tuple like (VALUE, OFFSET) in the variable item. So item[0] is VALUE and item[1] is OFFSET. And we print it.
I'll do this like:
my_list = [ ("VALUE1", "OFFSET1"), ("VALUE2", "OFFSET2") ]
def printList(my_llst):
values = []
ofts = []
for item in my_llst:
values.append(item[0])
ofts.append(item[1])
return (values,ofts)
(['VALUE1', 'VALUE2'], ['OFFSET1', 'OFFSET2'])
Since you have a list of tuples, instead of:
theValue = list[0].VALUE
theOffset = list[0].OFFSET
You can use:
theValue = list[0][0]
theOffset = list[0][1]
So in your for-loop:
def printList(list):
for item in list:
print('VALUE: {}'.format(item[0]))
print('OFFSET: {}'.format(item[1]))
If you want to get all values in list and offsets in a separate list, you can use list-comprehension:
values = [x[0] for x in list]
offsets = [x[1] for x in list]
One more important thing, AVOID using built-in functions like list as variables, use something else instead.
Try using a list comprehension
theValue = [value[0] for value in my_list]
theOffset = [offset[0] for value in offset]
I think namedtuple can help you.
from collections import namedtuple
Element = namedtuple("Element", ["value", "offset"])
element_list = []
for value, offset in my_list:
element_list.append(Element(value, offset))
for element in element_list:
print element.value, element.offset
If you want to get all values and offsets separately, you can use numpy to transform my_list to numpy.array which is a 2d array.
import numpy as np
2d_array = np.array(my_list)
values = 2d_array[:, 0]
offsets = 2d_array[:, 1]
I have a function h() that returns a tuple corresponding to the most common element in a list and its value from a dictionary called "Values" - so for example, if the most common element in list1 is a string "test" that occurs three times and that corresponds to Values = {"test":10}, then h(list1) = [3,10].
When two lists share the same element/frequency, I want to remove the most common element. Here is what I'm trying:
list1.remove([k for k,v in Values.items() if v == h(list1)[1]])
ValueError: list.remove(x): x not in list
How can I remove the key from a list based on its value in the Values dictionary?
Remove only expects a single element.
toremove = {k for k,v in Values.items() if v == h(list1)[1]]}
#either:
for r in toremove:
list1.remove(r)
#or (less efficient)
list1 = = [i for i in list1 if i not in toremove]
I'm trying to understand about dictionaries and list in Python.
Assume that I have a list which contains 3 dictionaries
Ex. item_list = [price,stock,quantity]
price, stock and quantity are the dictionaries here. Each dictionary has few key-value pairs like
price = {'toys':25,'clothes':[12,15,20]}
I know to access individual elements, I can use a for loop with the keys specified like:
for item in item_list:
print item['toys']
How do I access the elements without directly mentioning the key in the for loop?
You can iterate over a dictionary just like you can iterate over a list.
for item in item_list:
for key in item:
print item[key]
In a sense, you're still mentioning the keys, but you're not referencing them explicitly by their value.
If you're just interested in the values you can use the values() method:
for item in item_list:
for key in item.values():
print item[key]
My preferred way to iterate over dictionaries though is with items, which returns a tuple of key, value pairs.
for item in item_list:
for key, value in item.items():
print key, value
I would do something like this:
for item in item_list:
for key, value in item.iteritems():
print key, value
Let us say, you have a list like this
prices_list = [{'toys':25,'clothes':[12,15,20]},{'toys':35,'clothes':[12,15,20]}]
And you would like to get the value corresponding to toys, but without specifying the name in the for loop. So, you can use operator.itemgetter like this
from operator import itemgetter
getter = itemgetter("toys")
print [getter(item) for item in prices_list]
# [25, 35]
The same can be used like this
total = 0
for item in prices_list:
total += getter(item)
for d in item_list:
for i in d.values():
print i
You could also call d.items() and get back tuples of (key, value) if you wanted access to both.
Additionally if you don't care about readability you could use this to get a list of all the values accross the dicts in your list.
[x for y in (i.values() for i in item_list) for x in y]
You can also use: [d for i in item_list for d in i.values()] to get the values and flatten them into a list (though yours would still be nested because of clothes' value being a list.
Finally you can merge the dictionaries into one if they have distinct keys:
joint_mapping = dict([d for i in item_list for d in i.items()])
or if they don't have unique values you can use the below code to produce a dict of lists of values. :
for k, v in [d for i in item_list for d in i.items()]:
new_d[k] = new_d.get(k, [])+[v]
You mentioned :
#Eenvincible - I would be inputting those values to other variable.
Print is just an example I gave. So would not want to hardcode the key.
I think you can do your trick using for loop as mentioned in other answers.
for item in item_list:
for key in item:
print item[key]
tempvariable = item[key]
.... do something here.
If you want to assign each value to a seperate variable, you should:
- First, assign that variables to any insignificant value EX: **None** or *""*
- Then, dynamically use the for loop to reassign each variable to new value using if condition or thier index.
EX:
price_toys , price_clothes , stock_toys , stock_clothes = None , None , None , None
for item in item_list:
for key in item:
tempvariable = item[key]
# condition to choose which varible will be set to the current value.
if item == "price" and key == "toys":
price_toys = tempvariable
# and so on