How to remove dict where certain key is None - python

I want to delete a dictionary where certain key is None.
For example I have a list of dictionaries like:
my = [{"mydata": ""}, {"mydata": "hello"}]
What I did is:
for my_list in my:
if my_list["mydata"] == "":
my_list.clear()
But this gives:
[{}, {'mydata': 'hello'}]
I want that {} empty dictionary to be removed, How can I achieve it ?
My desired result format is :
{"my_data": "hello"}

Try this:
my = [{"mydata":""},{"mydata":"hello"}]
my2=[x for x in my if x['mydata']!='']
print(my2)

try list comprehension with any or all depending on your usecase.
In the example given by you if there is only one key in the dict then all and any won't make much difference.
my = [{"mydata":""},{"mydata":"hello"}]
my_new = [i for i in my if any(i.values())] #[{'mydata': 'hello'}]

Use List Comprehension
my = [{"mydata": ""}, {"mydata": "hello"}, {"mydata": "bye"}, {"mydata": ""}]
new_my = [{x: y} for i in my for x,y in i.items() if y != ""]
print(new_my)
[{'mydata': 'hello'}, {'mydata': 'bye'}]

Use remove() rather than clear(), and iterate over a copy of the list to avoid issues
for my_list in my[:]:
if my_list["mydata"] == "":
my.remove(my_list)

Related

Need help to remove empty lists from dictionaries

I have this dictionary:
a_dict = {1: "hello", 2: [], 3: [], 4: "hey", 5:"phone"}
And I want to remove all the empty lists from this dictionary.
Output: a_dict = {1:"hello",4:"hey",5:"phone"}
I tried this:
for item in a_dict:
if a_dict[item] == []:
del item
However, this just gives back the original dictionary. It doesn't do anything to it.
You should not be deleting key of a dict while you are iterating it. You can save your keys in some other variable and use it to delete keys. Here is a solution very much similar to your current code.
deleteKeys = []
for item in a_dict:
if a_dict[item] == []:
deleteKeys.append(item)
for i in deleteKeys:
del a_dict[i]

How to convert each items of list into a dictionary?

Here I have a list like this.
ls = ['Small:u', 'Small:o']
What I want is to create a dictionary of each list items like this.
dict1 = {'Small':'u'}
dict2 = {'Small':'o'}
How can I do it ? Is it possible?
>>> x = [dict([pair.split(":", 1)]) for pair in ['Small:u', 'Small:o']]
>>> x
[{'Small': 'u'}, {'Small': 'o'}]
Yes, it is possible, but one thing I'm not sure whether is possible (or a good idea at all) is to programmatically assign variable names to new dictionaries, so instead the easier way is to create a dictionary of dictionaries:
dic_of_dics = {}
for index, item in enumerate(ls):
i, j = item.split(':')
dic_of_dics[f'dict{index}'] = {i : j}
This is another way:
ls = ['Small:u', 'Small:o']
dict_list = []
for i in ls:
k, v = i.split(':')
dict_list.append({k: v})
print(dict_list)
print(dict_list[1].values())
Perhaps with minimal line:
ls = ['Small:u', 'Small:o']
dict_list = map(lambda x:dict([x.split(':')]), ls)
# for python3: print(list(dict_list))
# for Python2: print(dict_list)
Explanation: I am using map function to convert the list of string to list of lists. Then I am passing it through dict(to convert them to dictionary).

Get the values of a dictionary as list of values

I'm trying to obtain the values that are stored inside a dict but I couldn't do it.
dict = {"user": {"tw_id": [["1080231111188251398"], ["1080111112808902656"], [], ["1080081111173306369"], [], ["1080491111114200192"]]}}
I tried list(map(...) but I got a list of the characters as a result.
Please help!
I want to get a list like this:
list = ["1080231111188251398","1080111112808902656","1080081111173306369","1080491111114200192"]
Thank you
See How to make a flat list out of list of lists? For example:
# Using simpler data for readability
d = {"user": {"tw_id": [["a"], ["b"], [], ["c"], [], ["d"]]}}
from itertools import chain
L = list(chain.from_iterable(d['user']['tw_id']))
print(L) # -> ['a', 'b', 'c', 'd']
BTW don't use variable names like dict and list since they shadow the builtin types dict and list.
You can use a simple list comprehension to flatten, which accesses the first item of each subarray (assuming each subarray will only ever contain 1 item):
lst = [i[0] for i in dct["user"]["tw_id"] if i]
>>> dct = {"user": {"tw_id": [["1080231111188251398"], ["1080111112808902656"], [], ["1080081111173306369"], [], ["1080491111114200192"]]}}
>>> lst = [i[0] for i in dct["user"]["tw_id"] if i]
>>> lst
['1080231111188251398', '1080111112808902656', '1080081111173306369', '1080491111114200192']
>>>
Also, never use dict or list for variable names, it shadows the built-in.
Maybe I'm misunderstanding you, let me know if is the case.
you have a dict of dicts, so first of all you need to get the first level (users) then you will have a a dict where the value is a list.
> some = {"user": {"tw_id": [["1080231111188251398"], ["1080111112808902656"], [], ["1080081111173306369"], [], ["1080491111114200192"]]}}
> some["user"]
{'tw_id': [['1080231111188251398'], ['1080111112808902656'], [], ['1080081111173306369'], [], ['1080491111114200192']]}
> some["user"]["tw_id"]
[['1080231111188251398'], ['1080111112808902656'], [], ['1080081111173306369'], [], ['1080491111114200192']]

Find value in list of dicts and return id of dict

I'd like to try and find if a value is in a list of dicts, which can be done easily with:
if any(x['aKey'] == 'aValue' for x in my_list_of_dicts):
But this is only a boolean response, I'd like to not only check if the value is there, but to also access it afterwards, so something like:
for i, dictionary in enumerate(my_list_of_dicts):
if dictionary['aKey'] == 'aValue':
# Then do some stuff to that dictionary here
# my_list_of_dicts[i]['aNewKey'] = 'aNewValue'
Is there a better/more pythonic way of writing this out?
With next function, if expected to find only one target dict:
my_list_of_dicts = [{'aKey': 1}, {'aKey': 'aValue'}]
target_dict = next((d for d in my_list_of_dicts if d['aKey'] == 'aValue'), None)
if target_dict: target_dict['aKey'] = 'new_value'
print(my_list_of_dicts)
The output (input list with updated dictionary):
[{'aKey': 1}, {'aKey': 'new_value'}]
You can use a list comprehension. This will return a list of dictionaries that match your condition.
[x for x in my_list_of_dicts if x['aKey']=='aValue' ]

How do I find an item in an array of dictionaries?

Suppose I have this:
list = [ { 'p1':'v1' } ,{ 'p2':'v2' } ,{ 'p3':'v3' } ]
I need to find p2 and get its value.
You can try the following ... That will return all the values equivilant to the givenKey in all dictionaries.
ans = [d[key] for d in list if d.has_key(key)]
If this is what your actual code looks like (each key is unique), you should just use one dictionary:
things = { 'p1':'v1', 'p2':'v2', 'p3':'v3' }
do_something(things['p2'])
You can convert a list of dictionaries to one dictionary by merging them with update (but this will overwrite duplicate keys):
dict = {}
for item in list:
dict.update(item)
do_something(dict['p2'])
If that's not possible, you'll need to just loop through them:
for item in list:
if 'p2' in item:
do_something(item['p2'])
If you expect multiple results, you can also build up a list:
p2s = []
for item in list:
if 'p2' in item:
p2s.append(item['p2'])
Also, I wouldn't recommend actually naming any variables dict or list, since that will cause problems with the built-in dict() and list() functions.
These shouldn't be stored in a list to begin with, they should be stored in a dictionary. Since they're stored in a list, though, you can either search them as they are:
lst = [ { 'p1':'v1' } ,{ 'p2':'v2' } ,{ 'p3':'v3' } ]
p2 = next(d["p2"] for d in lst if "p2" in d)
Or turn them into a dictionary:
dct = {}
any(dct.update(d) for d in lst)
p2 = dct["p2"]
You can also use this one-liner:
filter(lambda x: 'p2' in x, list)[0]['p2']
if you have more than one 'p2', this will pick out the first; if you have none, it will raise IndexError.
for d in list:
if d.has_key("p2"):
return d['p2']
If it's a oneoff lookup, you can do something like this
>>> [i['p2'] for i in my_list if 'p2' in i]
['v2']
If you need to look up multiple keys, you should consider converting the list to something that can do key lookups in constant time (such as a dict)
>>> my_list = [ { 'p1':'v1' } ,{ 'p2':'v2' } ,{ 'p3':'v3' } ]
>>> my_dict = dict(i.popitem() for i in my_list)
>>> my_dict['p2']
'v2'
Start by flattening the list of dictionaries out to a dictionary, then you can index it by key and get the value:
{k:v for x in list for k,v in x.iteritems()}['p2']

Categories