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']]
Related
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)
I want to create a dictionary with dictionaries with empty lists inside. The nested dictionaries all have the same keys.
I have a solution already; but I really don't think it is smart:
outer_keys = ['out_a', 'out_b', 'out_c']
inner_keys = ['in_a', 'in_b', 'in_c']
dictionary = {}
for o in outer_keys:
dictionary[o] = {}
for i in inner_keys:
dictionary[o][i] = list()
This one works.
The result is:
{'out_a':
{'in_a': [],
'in_b': [],
'in_c': []},
{'out_b':
{'in_a': [],
'in_b': [],
'in_c': []},
{'out_c':
{'in_a': [],
'in_b': [],
'in_c': []}}
But is there a way to do it in a single line?
I tried
dictionary = dict([(o, {i: list()}) for o in outer_keys for i in inner_keys])
which unfortunately only saves the last inner_key and leads to:
{'out_a':
{'in_c': []},
'out_b':
{'in_c': []},
'out_c':
{'in_c': []}}
You can used a nested dict comprehension - the outer comprehension creates the dictionary, and for each key in it, another inner comprehension creates the inner dictionary
dictionary = {o: {i:list() for i in inner_keys} for o in outer_keys}
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]
I'm trying to create a list that contains multiple dictionaries with two keys, using a for loop, I'm trying to add elements to the first and second keys of each dictionary, however im not getting the expected output. the expected output that im hoping for for the following code would be:
XPECTED =====[{'parts':[2],F[]},{'parts':[3],F[]}]
a=[2,3]
list_combined=[]
dict={'parts':[],'F':[]}
for c in range(0,5):
list_combined.append(dict)
list_combined[c]['parts']=a[c]
1) The range(0, 5) will cause index error when you try to access a[c]
2) You are using the same dictionary in each iteration - so you keep modifying the same dictionary. You need to make a copy instead.
3) To get a list in parts you need to set that key to a list.
a = [2,3]
list_combined = []
d = {'parts': [], 'F': []}
for c in range(0, 2):
list_combined.append(d.copy())
list_combined[c]['parts'] = [a[c]]
print(list_combined)
Output:
[{'parts': [2], 'F': []}, {'parts': [3], 'F': []}]
It is not clear if the dictionary is created or modified but you can try this:
list_combined = [{'parts':[u],'F':[]} for u in a]
Also don't name your dictionary as dict because it is a keywords from Python.
I am not sure if this is a bug or a feature.
I have a dictionary to be initialized with empty lists.
Lets say
keys =['one','two','three']
sets = dict.fromkeys(keys,[])
What I observed is if you append any item to any of the lists all the lists are modified.
sets = dict.fromkeys(['one','two','three'],[])
sets['one'].append(1)
sets
{'three': [1],'two': [1], 'one': [1]}
But when I do it manually using loop,
for key in keys:
sets[key] = []
sets['one'].append(1)
sets
{'three': [], 'two': [], 'one': [1]}
I would think the second behavior should be the default.
This is how things work in Python.
When you use fromkeys() in this manner, you end with three references to the same list. When you change one list, all three appear to change.
The same behaviour can also be seen here:
In [2]: l = [[]] * 3
In [3]: l
Out[3]: [[], [], []]
In [4]: l[0].append('one')
In [5]: l
Out[5]: [['one'], ['one'], ['one']]
Again, the three lists are in fact three references to the same list:
In [6]: map(id, l)
Out[6]: [18459824, 18459824, 18459824]
(notice how they have the same id)
Other answers covered the 'Why', so here's the how.
You should use a comprehension to create your desired dictionary:
>>> keys = ['one','two','three']
>>> sets = { x: [] for x in keys }
>>> sets['one'].append(1)
>>> sets
{'three': [], 'two': [], 'one': [1]}
For Python 2.6 and below, the dictionary comprehension can be replaced with:
>>> sets = dict( ((x,[]) for x in keys) )