2

I'm working on a very beginner's setup and have to print sentences using the following dictionaries:

ast = {
    "number":6,"message":"success","people":
    [{"name":"Sergey Ryazanskiy","craft":"ISS"},{"name":"Randy Bresnik",
    "craft":"ISS"}, {"name":"Paolo Nespoli","craft":"ISS"}, {"name" : 
    "Alexander Misurkin","craft":"ISS"},{"name":"Mark Vande Hei","craft":"ISS"}
    ,{"name":"Joe Acaba","craft":"ISS"}]}

So I have to say something like:

  1. Sergey Ryanzanskiy

    • ISS
  2. Randy Bresnik

    • ISS

without bulletpoints (sorry, formatting) and am not sure how to refer to these keys. Additionally I have to create a sentence that will sum up the number of different crafts available but there is only one so I'm not sure how to create something to adjust to different names.

Help please!

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • start with: `for person in ast["people"]:` and you can use dictionary access to each person, meaning: `print(person["name"])` will display the person's name and etc. – Nir Alfasi Oct 27 '17 at 03:32
  • you can use `for v in ast["people"]: print v['name'], v['craft']` as well. – Mahesh Karia Oct 27 '17 at 03:43

4 Answers4

1

In python 3, using dictionary.items() returns an iterator of key-value pairs. You can print through them like this.

for key, value in d.items():
        print(key, value)

you can also print them directly:

for i in d:
    print (i, d[i])

You can add the numbering and format this however you want

EDIT: as mentioned, you can use list comprehensions. You could do something like

print_list = [(k,v) for k,v in d.items()]
for i in print_list:
    print (i, print_list[i]

this will print a numbered list of key/value tuples.

user2782067
  • 382
  • 4
  • 19
  • 1
    Or to get it faster, use list comprehensions: `[(k,v) for k,v in d.items()]` – skrubber Oct 27 '17 at 03:41
  • @sharatpc why is that faster ? – Nir Alfasi Oct 27 '17 at 03:45
  • @sharatpc I love my list comprehensions, but I am always a bit leery of recommending them to newbies. But i will update the post – user2782067 Oct 27 '17 at 03:47
  • @alfasin See this: [Loops et al](https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops) – skrubber Oct 27 '17 at 03:48
  • @sharatpc is that really faster than `list(d.items())`? – Jared Goguen Oct 27 '17 at 03:49
  • @sharatpc can you be more specific? I couldn't find anywhere that says that list comprehension is *faster* then its alternatives. – Nir Alfasi Oct 27 '17 at 04:11
  • @alfasin list comprehension, according to that doc, is 'syntactically more compact and more efficient way of writing the...for loop' – skrubber Oct 27 '17 at 04:17
  • Did you read the article your link directs to under [loop optimization](https://www.python.org/doc/essays/list2str/) ? I think that it's wrong to consider list-comprehension as "faster" by default, you should measure the alternatives and see it case-by-case. In [this](https://stackoverflow.com/a/43677631/1057429) example for-loops out preformed comprehension. – Nir Alfasi Oct 27 '17 at 04:19
  • @alfasin, I said list comprehension is faster than the answers with for loops per this qsn. I didn't intend to say they are faster than everything else. That's the reason I only provided computation time against the other two alternatives. – skrubber Oct 27 '17 at 04:24
  • @sharatpc I can see the answer that you deleted - you were comparing apples with oranges: in the for loop you printed every item - something that you didn't do while running comprehension, no wonder that performance were better. – Nir Alfasi Oct 27 '17 at 04:29
0

Ok I did this to print the names out but I'm still having a problem figuring out how to count the different types of craft when there's only one right now.

for person in ast["people"]: print(person["name"], "\n", person["craft"], "\n")

0

I'm still having a problem figuring out how to count the different types of craft when there's only one right now.

l = []
for p in ast['people']:
   if p['craft'] not in l:
      l.append(p['craft'])

then this number islen(l)

Simon Mengong
  • 2,625
  • 10
  • 22
  • the length of the list is 1 and comprises ISS only. don't quite get what you want? Your code needs a little formatting though and a colon at the end of the for loop – skrubber Oct 27 '17 at 04:22
  • @sharatpc I think he/she wants a way to do this programmatically, the code is correct – Simon Mengong Oct 27 '17 at 04:25
  • Having a counter incremented in the if loop and printing it outside the for loop will give 6. Also, can you run the code snippet above; I can't w/o the for loop having a colon – skrubber Oct 27 '17 at 04:44
0

I did the following code. it uses pandas

import pandas as pd

ast = {
    "number":6,"message":"success","people":
    [{"name":"Sergey Ryazanskiy","craft":"ISS"},{"name":"Randy Bresnik",
    "craft":"ISS"}, {"name":"Paolo Nespoli","craft":"ISS"}, {"name" :
    "Alexander Misurkin","craft":"ISS"},{"name":"Mark Vande Hei","craft":"ISS"}
    ,{"name":"Joe Acaba","craft":"ISS"}
    , {"name": "Erick Salas", "craft": "SSI"}]}

my_dataframe = pd.DataFrame(ast['people'])

print('People:')
print(my_dataframe[['name','craft']].to_string())
my_sum = my_dataframe['craft'].value_counts()
print('Count of crafts')
print(my_sum.to_string())


    People:
                 name craft
0   Sergey Ryazanskiy   ISS
1       Randy Bresnik   ISS
2       Paolo Nespoli   ISS
3  Alexander Misurkin   ISS
4      Mark Vande Hei   ISS
5           Joe Acaba   ISS
6         Erick Salas   SSI
Count of crafts
ISS    6
SSI    1