put values to dictionary Python - python

I want to put the data extracted from a dictionary into another dictionary. I want tu put what I got from that loop into list_od_id = []
for item in album['tracks']['data']:
print(item['id'])
list_of_id = []

for item in album['tracks']['data']:
list_of_id.append(item['id'])

So What I think your trying to say is you want the data of the dictionary to be put in a list.
There are 2 ways of doing this:
1:
dict = {"key1":"value1","key2":"value2","key3":"value3"}
values = []
for i in dict:
values.append(dict[i])
print("values: " + values)
2:
dict = {"key1":"value1","key2":"value2","key3":"value3"}
values = []
for key, value in dict.items():
values.append(value)
print(key + ": " + value)
print(values)

To add a certain value to a list use:
yourList.append(yourValue)
For your Code that would be:
list_of_id =[]
for item in album['tracks']['data']:
list_of_id.append(item['id'])
print(list_of_id)
EDIT
As it seems you confused a list with a dictionary.
your list_of_id is has the datatype list.
That means it is a Set of values.
A dictionary on the over hand Looks Like this:
myDictionary= {"Key": "value"}
Here you have one value for one Key.

quick solution for create new list of item['id'].
list_of_id = [item['id'] for item in album['tracks']['data']]

Related

Find a value of Key in Json Array - Python

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

How do I save changes made in a dictionary values to itself?

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])

How to parse Python set-inside-list structure into text?

I have the following strange format I am trying to parse.
The data structure I am trying to parse is a "set" of key-value pairs in a list:
[{'key1:value1', 'key2:value2', 'key3:value3',...}]
That's the only data I have, and it needs to be processed. I don't think this can be described as a Python data structure, but I need to parse this to become a string like
'key1:value1, key2:value2, key3:value3'.
Is this doable?
EDIT: Yes, it is key:value, not key:value
Also, this is Python3.x
Iterating over .items() and formatting differently then previous answers.
If your data is the following: list of dict objects then
>>> data = [{'key1':'value1', 'key2':'value2', 'key3':'value3'}]
>>> ', '.join('{0}:{1}'.format(*item) for item in my_dict.items() for my_dict in data)
'key2:value2, key3:value3, key1:value1'
If you data is the list of set objects then approach is simpler
>>> from itertools import chain
>>> data = [{'key1:value1', 'key2:value2', 'key3:value3'}]
>>> ', '.join(chain.from_iterable(data))
'key1:value1, key2:value2, key3:value3'
UPD
NOTE: order can be changed, because set and dict objects are not ordered.
', '.join('{0}:{1}'.format(key, value) for key, value in my_dict.iteritems() for my_dict in my_list)
where my_list is name of your list variable
Since your structure (let's call it myStruct) is a set rather than a dict, the following code should do what you want:
result = ", ".join([x for x in myStruct[0]])
Beware, a set is not ordered, so you might end up with something like 'key2:value2, key1:value1, key3:value3'.
I would use itertools
d = {'key1':'value1', 'key2':'value2', 'key3':'value3'}
for k, v in d.iteritems():
print k + v + ',',
So, you have a list whose only element is a dictionary, and you want to get all the keys-value pairs from that dictionary and put them into a string?
If so, try something like this:
d = yourList[0]
s = ""
for key in d.keys():
s += key + ":" + d[key] + ", "
s = s[:-2] #To trim off the last comma that gets added
Try this,
print ', '.join(i for x in list_of_set for i in x)
If it's set there is no issue with the parsing. The code is equals to
output = ''
for x in list of_set:
for i in x:
output += i
print output

Print both the duplicate values name from the nested list

students=[['Ash',85.25],['Kai',85.25],['Ray',75],['Jay',55.5]]
output:Ash
Kai
I'm trying to solve a task and i'm new in python.I am not getting what i want can anyone explain me how one can do it
One option would be to group the values into a defaultdict(list):
>>> from collections import defaultdict
>>>
>>> students = [['Ash',85.25],['Kai',85.25],['Ray',75],['Jay',55.5]]
>>> d = defaultdict(list)
>>> for value, key in students:
... d[key].append(value)
...
>>> for value in d.itervalues():
... if len(value) > 1:
... print(value)
...
['Ash', 'Kai']
I would do it like that:
students = [['Ash', 85.25], ['Kai', 85.25], ['Ray', 75], ['Jay', 55.5]]
common_names = []
for i, i_x in enumerate(students):
for i_y in students[:i] + students[i + 1:]:
if i_x[1] == i_y[1]:
common_names.append(i_x[0])
print(common_names)
#['Ash', 'Kai']
# or if you want it to print every entry in a single line:
print('\n'.join(x for x in common_names))
#Ash
#kai
Explain:
I grab an object from the original list students. Object is i_x and its ['Ash', 85.25] on the first iteration for example.
Then i slice the list students[:i] + students[i + 1:] to create another one in memory that contains all the elements of the original one apart from i_x
I check to see if there is any item in the newly created list that has the same [1] index value as that of i_x. If yes, i append the i_x[0] value to a third list that holds the results.
I do this for as many elements as there are originally in the students list.
Can anybody provide a list comprehension for the above?

How to access dictionary elements in a list in python

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

Categories

Resources