-1

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

Agustin
  • 5
  • 1
  • See https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists for how to flatten the list of lists. Do that for each dictionary element, and concatenate the results. – Barmar Jun 22 '20 at 23:48

3 Answers3

1

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

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.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
0

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']]
Carlos Rojas
  • 334
  • 5
  • 13