Resolved: Dictionaries and List comprehension
How can I solve this problem? Using a list comprehension
- Read each entry in the string arrays into dictionary objects to create two lists of dictionaries
- Iterate over the two lists, first_list and second_list one at a time and produce two new lists of dictionaries.
- Call them first_dicts and second_dicts.
- Print the first 2 entries in each list
Hey Jaiswal,
I think you actually offer an interesting problem in its own right, which is very nice.
Would you mind expanding it a bit, maybe give a small example of what needs to be done?
----------------------------------------
To my mind, you have two lists of 'string' objects (which are first_list & second_list) and you want to use a list comprehension to produce
a set of two dictionaries. If that is the case, I would assume the two dictionaries have the same key-value pairs, but swapped (this may not
be the case; if you have something different in mind, do let us know by writing here again ;)). The following code does the trick:
----------------------------------------
I would also like to offer a brief explanation to the code. When you need to iterate two (or more) lists (or iterables, generally) simultaneously,
you can always opt for the zip function. It produces tuples of size = the number of lists.
When you write - ... for (first_str, second_str) in zip(first_list, second_list), you iterate over both lists, namely - first_str iterates over first_list
and second_str iterates over second_list. To get dictionaries, you just need to place whatever you need in curly brackets {entry_1 : entry_2}.
----------------------------------------
Let us know if more clarification is needed or the problem is different (sorry for the misunderstanding, if that is the case).
On a positive note, maybe the picture can help you get the result you are looking for. The code is a very popular way to iterate over two
lists in a list comprehension. If you can adapt it to your needs,it would be wonderful. You can always drop a line to share a success story :)
Regards,
A., The 365 Team
Hi Sir Atanas!
I appreciate the very prompt response and the explanation and code you provided. This is indeed a logic i can apply in the future.
Thank you!
However,
I would like to adress that the confusion was caused by my comprehension to the original question and my phrasing!
For that I am sorry, and let me rephrase:
I think it would be easier if I narrow it down to only one list since the 2 lists have nothing to do with each other, so minus the zip function
Suppose I already have a list called reviewers_list which contains:
[{'username':'blabla', 'DOB':'xxx', 'reviewed': ["asdasd"]},
{'username':'bleble', 'DOB':'xxx', 'reviewed': ["aasdddd"]},
{'username':'blublu', 'DOB':'xxx', 'reviewed': ["wwwwwww"]}]
I would like to iterate over this list and produce a new list of dictionary which i want to call reviewers_dicts
And I want to do that using a list comprehension.
After that I would like to print out the first 2 entries of the list.
Here was my attempt:
reviewers_dicts = [{rev for rev in reviewers_list}]
reviewers_dicts[:2]
The problem is that I am returning every entries instead of only the "first 2" entries of the list, which would be:
[{'username':'blabla', 'DOB':'xxx', 'reviewed': ["asdasd"]},
{'username':'bleble', 'DOB':'xxx', 'reviewed': ["aasdddd"]},]
Hey,
I am glad you found the previous answer helpful, thank you for your remarks and explanation :)
Now, let us address in detail your worked example. We have a list of dictionaries, which you call reviewers_list. You want to iterate
over the list to produce a similar list, but with the help of list comprehensions. If that is the case, please take a look at the following code:
-----------------------------------
Let us talk a bit about list comprehensions. The code displayed, [d for d in reviewers_list], works because each entry of the reviewers_list
is a dictinary (and you want to produce a list of dictionaries). That is how list comprehensions work in general - if you write [x for x in iterable],
then x can be a tuple (if iterable is a list of tuples) or x can be a dictionary, like in our case. The reason why
reviewers_dicts = [{rev for rev in reviewers_list}] won't work is subtle - notice you need to place 'for' outside of the curly brackets. Because every
element is a dictionary, you don't need them in this example - a loop is quite enough.
-----------------------------------
Don't worry - it can be some pain at first, but when you get used to using them, it is really helpful. I encourage you to work out some small
examples on your own, too. Let us know how you are finding this answer. I will try and search for some additional examples and post them
here, if you like.
Best Regards,
A., The 365 Team
Oh! so it was just removing the curly brackets! Thank you so much! May I call for your help again soon!
Hey,
Glad I could help! If you have any further questions down the road, we'd be looking forward to assist :)
I did a quick search for 'list comprehension examples' and want to share with you this page: https://realpython.com/list-comprehension-python/
Real Python is a very informative website about all things Python, with many examples and use-cases. So if you are interested, you can read up
a bit about list comprehensions there (maybe not everything, it's a long article, but the examples are very thorough and practical).
Cheers,
A., The 365 Team
I would love to add that on my cheat sheets! Thank you so much! May I shoot another question here or should I post it as another question?
I'm just gonna post it here for now. Do tell me if I have made the wrong move! :D
Suppose I have a Json file dummy.json. I would like to open it and read its contents into a string.
Here is another phrasing: I want to open dummy.json and store the text it contain into a string variable called
dummy_string. After that, I would like to print the first 500 characters of dummy_string.
Here was my attempt:
dummy_string = open('dummy.json','r')
for char in dummy_string:
print(char[0:500])
dummy_string.close()
The problem I am encountering is that I am printing the first 500 entries instead of only the first 500 characters.
Also, following up the output of the list comprehension,
How do i prove that the entries in the list is a dictionary?
Here was my attempt:¨
type(products_dicts[0])
and it outputs:
str
Hey Jaiswal,
Of course, you can ask freely as you like, my only piece of advice is -- if you mark a question as resolved, it's better to post a new topic in the Q&A section.
It's just a bit of organisation, also, think about other students having the same issues. Different questions can help them navigate their way better to the
answers.
----------------------------
Now, on to the first question. You have a dummy.json file. A JSON is a special file format and Python comes with built-in tools to manipulate json files.
This is where you need to decide do you work with dummy.json as a regular text file (including '{', '}', '[', ']', etc. as characters) or you need to work with it
like you would with a json file. I will give a small example for both, then you will make your mind what you really need and adapt it to your situation.
Reading from a text files is done with readlines() - see appropriate lecture on I/O operations with Python. Note that every time you read the file, you need
to use seek(0) to return to the beginning if you wish to read again!
-----------------------------
I attach ny code using a json file I got from https://jsonplaceholder.typicode.com/. My dummy.json is actually the 'comments' json file.
I hope you will be able to reproduce the results and see that if you want to print the first 500 characters, there are minor changes you have to take care of.
As for the list comprehension, use a print() statement to see what products_dicts[0] is. Maybe you need to change the indexing?
------------------------------------
Best regards,
A., The 365 Team
Hey!
What should be the indexing be? any suggestion?
products_dicts[0] outputs a dictionary structured data, but if i check it's type type(products_dicts[0]), it says it's a 'str'
Hi,
If products_dicts[0] has a set of quotes '...', this is still a string. I would assume you are reading from the json file, which consists of various
dictionary-like entries. If you want to convert such a string to a dictionary, you can use dict(my_str), where my_str is the string in question.
Otherwise, I would suggest looking up online the workflow with json files in python. Without knowing what you aim to achieve, we can only
offer some general tips.Still, I think you can cast to dictionary and be able to proceed smoothly from there on.
Regards,
A. The 365 Team
I understand, but hey, trying out the codes you provided made some things clear to me. Thanks for that! I will try things out first and I will post again!
Sure, we are always looking forward to interesting questions!
Delighted to have helped!
Hey! I Referring to what you've said previously. This is indeed the problem
if products_dicts[0] has a set of quotes '...', this is still a string. I would assume you are reading from the json file, which consists of various
dictionary-like entries. If you want to convert such a string to a dictionary, you can use dict(my_str), where my_str is the string in question.
here is my output:
['{"Username": "bkpn1412", "DOB": "31.07.1983", "State": "Oregon", "Reviewed": ["cea76118f6a9110a893de2b7654319c0"]}\n',
'{"Username": "gqjs4414", "DOB": "27.07.1998", "State": "Massachusetts", "Reviewed": ["fa04fe6c0dd5189f54fe600838da43d3"]}\n']
It's from this one:
reviewers_dicts = [rev for rev in reviewers_list]
reviewers_dicts[:2]
How do I make the outputs be dictionary entries instead of string?
Hey! Actually, using the aforementioned 'json' library is probably the easiest solution. Here is an example how to use json.loads() to convert
a string representation of a dictionary to a dictionary:
>>> import json
>>> str_dict = '{"key1":"value1", "key2":"value2"}'
>>> real_dict = json.loads(str_dict)
>>> real_dict
{'key1':'value1', 'key2':'value2'}
>>> type(d)
<class 'dict'>
This is how you can transoform a string. If you have a list of strings, each being a dictionary-like string, you can use Python's map function to
produce a list of real dictionaries:
>>> list_of_str_dicts = ['{"key1":"value1"}', '{"key2":"value2"}']
>>> list(map(json.loads, list_of_str_dicts))
[{"key1":"value1"}, {"key2":"value2"}]
Hope that helps!
Regards,
A., The 365 Team
You're a Python God :D you're one of the reason this platform is the best! Thank you!
You are most welcome! Thank you very much for the kind words!
Stay curious and eager to learn! :)
---
Best,
A., The 365 Team
Hey sir Atanas, I tried posting another question but it did not appear so I'm just continuing at this thread:
I have a list of dictionaries called reviewers_dicts.
here is a sample output of what 'reviewers_dicts' contains:
In: print(reviewers_dicts[:2])
Out: [{'Username': 'bkpn1412', 'DOB': '31.07.1983', 'State': 'Oregon', 'Reviewed': ['cea76118f6a9110a893de2b7654319c0']},
{'Username': 'gqjs4414', 'DOB': '27.07.1998', 'State': 'Massachusetts', 'Reviewed': ['fa04fe6c0dd5189f54fe600838da43d3']}]
I want to write a function called 'find_user' where it should take one argument and return the dictionary from reviewers_dicts
that contains the given username in its Username field. If the username is not found, it should return None.
Test it by calling it with sample user name = krpz1113
Here was my attempt,
def find_user(Username):
for k in reviewers_dicts:
return k
find_user('krpz1113')
#This outputs:
{'Username': 'aaez2213',
'DOB': '06.08.1959',
'State': 'Minor Outlying Islands',
'Reviewed': ['02f7779ab84319cdf752177315b9cf4f',
'0ae2c0dbb749d34315e7be47da3a7020',
'c58b4d51ec411b8803472e6ddc320ab6',
'f89b4212c3123a11674726ebd8c7f25c']}
#I kinda understand why, so I also tried adding if statement, but it only threw errors.
Please help :D
Hi both,
I see that this question has been resolved. In the future I suggest that you post a question directly under the lecture it is related to.
This is extremely important as it helps the author or tutor, responsible for each course to find the question and see what it's related to quickly.
In addition, this helps other students find relevant answers to course content questions and maybe find answer to their own queries.
To your last question, I suggest you take a look at the course content we have available, and particularly the course Introduction to Python and the Python Programmer Bootcamp. Please make sure to watch all lectures and complete all exercises, as we've really invested a great deal in creating a comprehensive and worthwhile learning experience. Here's a link to both:
Introduction to Python Course | 365 DataScience
Python Programmer Bootcamp Course | 365 DataScience
Please be mindful that we cannot troubleshoot every problem you encounter when programming when it is not directly related to the content of the course.
What's more, from my own experience I have learned that the truly best way to learn programming, is to try and tackle the problems on your own, because this is the only way to really understand what the code is actually doing.
Hope this helps!
Best,
365 Eli
Hallo
Im using window xp 7 and im struggling to download Python software is say it fail to install what should I do?
Or which one software is the best?