Im just starting to learn practice it however my problem I bet is easy to resolve I’m trying my best but my knowledge is too low to solve this out , I’ve try commas brackets but still didn’t work I just want to get print the name country and age , sorry for newbie question please help 👍🏼💪🤠
Main.py
import one
a = one.person1["name"]
b = one.person2["name"]
c = one.person3["name"]
def input():
print(one(name))
One.py
person1 = {
"name": "John",
"age": "6",
"country": "Norway"
}
person2 = {
"name": "Jn",
"age": "36",
"country": "Norway"
}
person3 = {
"name": "krun",
"age": "36",
"country": "Norway"
}
If you want to display one person then use every key separatelly
print( one.person1["name"], one.person1["age"], one.person1["country"] )
And then you can format output
print('name =', one.person1["name"])
print('age =', one.person1["age"])
print('country =', one.person1["country"])
You can also display directly print(one.person1) but then you can't format output.
If you want to display all persons then keep them on list and then you can use for-loop
persons = [one.person1, one.person2, one.person2]
for item in persons:
print( item["name"], item["age"], item["country"] )
If you don't know keys then you can use .keys() or .items() in dictionary
for item in persons:
for key, value in item.items():
print(key, '=', value)
if you want to get key from user then
key = input("what to show: ")
print(one.person1[key])
print(one.person2[key])
print(one.person3[key])
or better keep persons on list and use for-loop
key = input("what to show: ")
persons = [one.person1, one.person2, one.person2]
for item in persons:
print( item[key] )
Related
im trying to the below code but when I run the function for examnple:
finder("001-987654-003")
Nothing is happening. What went wrong?
def finder(lookupvalue):
user_list = [
["Account number","Currency","Balance"],
["001-987654-003","USD",1300.72],
["001-919202-100","EUR",105.01],
["001-905700-100","EUR",305.00],
["001-908415-307","CHF",20804.98],
["011-974777-200","PLN",208.15],
["001-931654-001","USD",450.7]
]
for row in user_list:
if user_list[0][0]==lookupvalue:
print("yes")
You have to use row instead of user_list:
def finder(lookupvalue, lookuplist, col_index):
for row in lookuplist:
if row[0] == lookupvalue:
print(row[col_index - 1])
finder("001-919202-100", user_list, 2)
That's because if you use user_list[0][0] in the for loop it'll constantly refer to "Account number" whilst row[0] will go through the different lists, looking up the account number.
But as one of the comments said, a dictionary would probably be better for this task.
try this:
user_list = [
["Account number", "Currency", "Balance"],
["001-987654-003", "USD", 1300.72],
["001-919202-100", "EUR", 105.01],
["001-905700-100", "EUR", 305.00],
["001-908415-307", "CHF", 20804.98],
["011-974777-200", "PLN", 208.15],
["001-931654-001", "USD", 450.7]
]
def finder(lookupvalue, lookuplist, col_index):
for row in user_list:
if row[0] == lookupvalue:
print(row[col_index-1])
finder("001-919202-100", user_list, 2)
output:
EUR
Try using a dictionary:
user_list = {
"Account Number": ["001-987654-003", "001-919202-100", "001-905700-100"],
"Currency": ["USD", "EUR", "EUR"],
"Balance": [1300.72, 105.01, 305.00]
}
Seems more appropriate in your case as you're trying to store different lists (I think).
Here is my working example
jsonData = {
"3": {
"map_id": "1",
"marker_id": "3",
"title": "Your title here",
"address": "456 Example Ave",
"desc": "Description",
"pic": "",
"icon": "",
"linkd": "",
"lat": "3.14",
"lng": "-22.98",
"anim": "0",
"retina": "0",
"category": "1",
"infoopen": "0",
"other_data": ["0"]
},
"4": {
"map_id": "1",
"marker_id": "4",
"title": "Title of Place",
"address": "123 Main St, City, State",
"desc": "insert description",
"pic": "",
"icon": "",
"linkd": "",
"lat": "1.23",
"lng": "-4.56",
"anim": "0",
"retina": "0",
"category": "0",
"infoopen": "0",
"other_data": ["0"]
}
I am having such a hard time getting the title and address keys. Here is what I have tried:
for each in testJson:
print(each["title"])
and I get the following error TypeError: string indices must be integers. I don't understand why this isn't working.
I have tried so many variations to get the key data, but I just can't get it to work. I can't really change the raw JSON either because my real JSON data is a huge file. I have looked on stackoverflow for a similarly formatted JSON example (e.g., here) but have come up short. I assume there is something wrong with the way my JSON is formatted, because I have parsed JSON before with the above code without any problems.
Your getting that error because your looping over the keys, which don't have title and address properties. Those properties exist in the inner dictionaries, which are the values of the dictionary.
Here is how you can iterate over the dict.values() instead:
for value in jsonData.values():
print(value["title"], value["address"])
Which will give you the title and address:
Your title here 456 Example Ave
Title of Place 123 Main St, City, State
If you want to find out which key your iterating over, you can loop over the tuple (key, value) pair from dict.items():
for key, value in jsonData.items():
print(f"key = {key}, title = {value['title']}, address = {value['address']}")
Which will show the key with the address and title:
key = 3, title = Your title here, address = 456 Example Ave
key = 4, title = Title of Place, address = 123 Main St, City, State
for… in loops iterate over the keys of dictionaries, not their values. If you want to iterate over their values, you can either use .values():
for value in someDict.values():
…or you can iterate over items(), which will give you the key and the value as a tuple:
for key, value in someDict.items():
The reason why you are getting the error message you are is because when you try to get title out of each, each is actually the key, .i.e. "3" or "4". Python will let you get individual characters out of a string with things like someString[0] to get the first character, but it doesn't make sense to access things like someString['title'].
I have a JSON file which I would like to manipulate, I know this may sound basic but my question is, based on User1 + Country, how do I list all the other Users that falls under any of the listed countries based on User1
EDIT: Getting Name instead of the UserID, I realised I can't use Key,Value, how do I go around that?
{
"user1":{
"Country":[
"China, USA, Nepal"
],
"Name": [
"Lisbon"
],
},
"user2":{
"Country":[
"Sweden, China, USA"
],
"Name": [
"Jade"
],
},
"user3":{
"Country":[
"India, China, USA"
],
"Name": [
"John"
],
}
}
Here's what I've done so far
userName= raw_input("Enter user's name: ")
with open('listOfUsers.json') as f:
data = json.load(f)
for k, v in data.items():
print str(dict[k][v])
That will do what you want:
def getId(name):
for userId, v in data.items():
if v['Name'] == name:
return userId;
id = getId(userName)
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
print(k)
But only when you fix your json. Your lists of countries have only one string.
["China", "USA", "Nepal"] instead of ["China, USA, Nepal"]
With your json, you could do something like this using the
set.intersection method:
userName= raw_input("Enter user's name: ")
with open('listOfUsers.json') as f:
data = json.load(f)
# get username Country
user_country = data.get(username, {}).get("Country", [])[0].split()
user_country_set = set(user_country)
# then filter all users having same Country
users = [u for u, v in data.items() if set(v["Country"][0].split()).intersection(user_country_set) ]
But, if you can control the input json format, I would suggest using:
"Country":[
"China", "USA", "Nepal"
]
instead, which would greatly simplify the code into:
user_country = data.get(username, {}).get("Country", [])
user_country_set = set(user_country)
# then filter all users having same Country
users = [user for user, d in data.items() if set(d.get("Country", [])).intersection(user_country_set) ]
I'm currently trying to search for entries inside my Redis that match a specific value through an HTTP API the same way you'd do with a regular DB (eg: http://localhost:8000/api?name=John&age=20) with the redis python library (https://pypi.org/project/redis/).
The code I have thus far returns the whole hash, converts each entry into a JSON and adds it to a list
import json
import redis
import os
r = redis.StrictRedis(host=os.environ['redis_url'], port=os.environ['redis_port'], password=os.environ['redis_pass'], ssl=True)
result = r.hgetall('Directory')
dic_list = []
for key in result.keys():
dic_list.append(json.loads(result[key].decode('utf-8')))
return dic_list
I know that I can get the value of a specific key with
r.hget('Directory', 'key_I_want')
However inside each key there is a whole JSON full with information, so for example this would be a key, value example inside of the Directory hash
"1": {
"name": "James",
"age": "22",
"favorite_color":"Green"
},
"2":{
"name":"John",
"age": "20",
"favorite_color": "red"
},
"3":{
"name":"Jim",
"age": "30",
"favorite_color": "yellow"
}
So I know
r.hget('Directory', '1')
would return
{
"name": "James",
"age": "22",
"favorite_color":"Green"
}
But what I really want is to look for every JSON that has specific values, not just to get the values of each key inside the hash, is there any way to actually do that?
Based on your question, you are, maybe, looking for a value within results[key]. Assumin that value is equal to val, try:
for key in result.keys():
if val in result[key].values():
dic_list.append(json.loads(result[key].decode('utf-8')))
for example, if
val = "James"
Yoy will get all results with James in the value.
You can mix it up a little, change it the way you want it.
Please see the JSON below taken from an API.
my_json =
{
"cities":[
{
"portland":[
{"more_info":[{"rank": "3", "games_played": "5"}
],
"team_name": "blazers"
},
{
"cleveland":[
{"more_info":[{"rank": "2", "games_played": "7"}
],
"team_name": "cavaliers"
}
]
}
I would like to create a new dictionary from this my_json with "team_name" as the key and "rank" as the value.
Like this: {'Blazers': 3, 'Cavaliers': 2, 'Bulls': 7}
I'm not sure how to accomplish this... I can return a list of cities, and I can return a list of ranks, but they end up being two separate lists with no relation, I'm not sure how to relate the two.
Any help would be appreciated (I'm also open to organizing this info in a list rather than dict if that is easier).
If I run this:
results_dict = {}
cities = my_json.get('cities', [])
for x in cities:
for k,v in x.items():
print k, v
it returns:
team_name blazers
portland [{"rank": "3", "games_played": "5"}
team_name cavaliers
cavaliers [{"rank": "2", "games_played": "7"}
If you want to take your cities list and your ranks list and combine them, you could use zip() and a dictionary comprehension:
output = {city: rank for city, rank in zip(cities, ranks)}
Valid JSON looks like:
{
"cities":[
{
"portland":[
{"more_info":
[{"rank": "3", "games_played": "5"}],
"team_name":
"blazers"
}
]
},
{
"cleveland":[
{"more_info":
[{"rank": "2", "games_played": "7"}],
"team_name":
"cavaliers"
}
]
}
]
}
This part of code returns all you want, but I'll try to write more readable code instead of this:
results_dict = {}
cities = my_json.get('cities', [])
for x in cities:
for k,v in x.items():
for element in v:
team = element.get('team_name', '')
meta_data = element.get('more_info', [])
for item in meta_data:
rank = item.get('rank')
results_dict.update({team: rank})
>>> results_dict
{'blazers': '3', 'cavaliers': '2'}
What API is that? The JSON structure (if pivanchy got it right) seems to be unnecessarily nested in lists. (Can a city have more than one team? Probably yes. Can a team have more than one rank, though?)
But just for sports, here is a gigantic dictionary comprehension to extract the data you want:
{ team['team_name']: team['more_info'][0]['rank']
for ((team,),) in (
city.values() for city in my_json['cities']
)
}
The json seemed to be missing some closing brackets. After adding them I got this:
my_json = {
"cities": [
{"portland":[
{"more_info":[{"rank": "3", "games_played": "5"}],"team_name": "blazers"}]},
{"cleveland":[{"more_info":[{"rank": "2", "games_played": "7"}],"team_name": "cavaliers"}]}
]
}
Given that structure, which is extremely nested, the following code will extract the data you want, but its very messy:
results = {}
for el in my_json["cities"]:
name = el.keys()[0]
rank = el.values()[0][0]["more_info"][0]["rank"]
results[name] = rank
print results
Which will give you:
{'portland': '3', 'cleveland': '2'}