#๐Ÿ”’ question about dictionaries

145 messages ยท Page 1 of 1 (latest)

chrome tangle
#

how can i assign a new value to a key of a dictionary thats already inside another dictionary without directly using the key's text(working with external jsons)code:
import json
brands = {1: 'lamtechfile.json'
, 2: 'celebratfile.json'}
lamtechitems = {1: 'type c to type c',
2: 'type c to usb'}

def viewproducts():
answer = int(input('What brand do you want to view?\n1. Lamtech\n2. Celebrat'))
with open(brands.get(answer), 'r') as file:
viewbrands = json.load(file)
for key, value in viewbrands.items():
print(key, ':', value)

def addsupply():
answer1 = int(input('From which brand do you want to chnange supply?\n1. Lamtech\n2. Celebrat'))
with open(brands.get(answer1), 'r') as file:
viewbrands = json.load(file)
for key, value in viewbrands.items():
print(key, ':', value)
items = []
for i in viewbrands:
items.append(i)
for x, y in enumerate(items, start=1):
print(x, y)
answer2 = input('Which item do you want to change the supply of?: ')
answer3 = input('What number do you want to set the supply to?')
viewbrands[lamtechitems.get(answer2)] = answer3
with open(brands.get(answer1), 'w') as file2:
json.dump(viewbrands, file2, indent=2)

earnest mortarBOT
#

@chrome tangle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

chrome tangle
#

yes i might be trying to make a database using jsons

#

need help quick otherwise im failing in being a good son

barren burrow
#

could you clarify what you mean with an example? don't quite understand what key that is already inside another dictionary means here

chrome tangle
#

uh

#

wait

#

im changing the question because i added unnecessary things

golden herald
#

what Stickie said, I'm also not sure what you mean
this?

>>> d = {'a': 10, 'b': 5}
>>> e = {'a': -1, 'c': 15}
>>> {k: e.get(k, v) for k, v in d.items()}
{'a': -1, 'b': 5}
>>>
golden herald
chrome tangle
#

i have this json

#

{
"type c to type c": 3,
"type c to usb": 2,
}

zenith crypt
#

if any(k in dict1 for k in dict2)?

chrome tangle
#

the user is asked which json he wants to view

#

lets say only this for now

chrome tangle
#

i want to be able to let the user change a value for example make the 2 three

#

thats what im trying to ask but my english sucks

zenith crypt
#

dict[key]=value?

chrome tangle
#

yes but the issue is

barren burrow
chrome tangle
chrome tangle
zenith crypt
#

if u want to only change and never add new entrys

chrome tangle
#

the issue isnt the key not being in the dict

#

shouldnt this line do what i want? : viewbrands[lamtechitems.get(answer2)] = answer3

zenith crypt
#

no

#

u just need to check if the key is present or not u can do that by
key in dict

chrome tangle
#

but the key IS present

#

now it worked because i changed viewbrands[lamtechitems.get(answer2)] = answer3 to viewbrands['type c to type c'] = answer3

zenith crypt
chrome tangle
#

type c to type c is what the get(asnwer2) correpsonds to

zenith crypt
zenith crypt
chrome tangle
zenith crypt
chrome tangle
#

though

zenith crypt
#

u want to merge the 2 dicts with the user selecting which of the 2 values to keep?

chrome tangle
#

no

#

the user first inputs which dict he wants to see, then he specifies an item and then a new value for the specific item\

zenith crypt
#

i still dont get why the 2 dicts?
why not 1?

chrome tangle
zenith crypt
chrome tangle
#

yes but

#

why doesnt python find the key

#

if its already in

#

and instead it creates a null key

zenith crypt
chrome tangle
#

ye

#

lemme show u what happens

zenith crypt
#

use !e

chrome tangle
#

?

zenith crypt
#

!e
d={"a":1}
print(d.get("a"))
print(d.get("c"))

earnest mortarBOT
chrome tangle
#

no not that

#

wait

#

initial dict is this: {
"type c to type c": 3,
"type c to usb": 2,
}

#

after running my code it turns into this: {
"type c to type c": 3,
"type c to usb": 2,
"null": "1"
}

zenith crypt
#

wait
if the key is in both dicts u .get the value and the value isnt in the dict as a key ofc

zenith crypt
chrome tangle
#

so should i just send the func?

zenith crypt
chrome tangle
#

ok

#
        viewbrands['type c to type c'] = answer3
    with open(brands.get(answer1), 'w') as file2:
        json.dump(viewbrands, file2, indent=2)
#

@zenith cryptthis is where it goes wrong

zenith crypt
chrome tangle
#

the lamtech dict

zenith crypt
#

!e
d={
"type c to type c": 3,
"type c to usb": 2,
}
d['type c to type c']=10
print(d)

earnest mortarBOT
chrome tangle
#

if i change the with open to have 'type c to type c' instead of brands.get(answer1) it works fine

zenith crypt
chrome tangle
#

no way i did what i think i did

zenith crypt
#

when do u set it to what?

chrome tangle
#

wait

zenith crypt
#

the answer1

chrome tangle
#

it should have answer2 shouldnt it

#

omg

zenith crypt
#

answer1 may not be 'type c to type c' if 'type c to type c' works but answer1 doesnt

chrome tangle
#

what??

zenith crypt
chrome tangle
#

let me see

#

it saves the value as the one i insert

#

but it also creates a new key with the same value

#

also for some reason the json file doesnt have the null : 1 but the func returns it anyways

#

ykw fuck this im giving up

wanton hamlet
#

can you explain in brief what you did, what you expected, and what you actually observed?

#

also please use code formatting

wanton hamlet
#

what code you wrote.

zenith crypt
#

and what inputs u gave it

chrome tangle
#
import json
brands = {1: 'lamtechfile.json'
          , 2: 'celebratfile.json'}
lamtechitems = {1: 'type c to type c',
                2: 'type c to usb'}

def viewproducts():
    answer = int(input('What brand do you want to view?\n1. Lamtech\n2. Celebrat'))
    with open(brands.get(answer), 'r') as file:
        viewbrands = json.load(file)
        for key, value in viewbrands.items():
            print(key, ':', value)

def addsupply():
    answer1 = int(input('From which brand do you want to change supply?\n1. Lamtech\n2. Celebrat'))
    with open(brands.get(answer1), 'r') as file:
        viewbrands = json.load(file)
        for key, value in viewbrands.items():
            print(key, ':', value)
        items = []
        for i in viewbrands:
            items.append(i)
        for x, y  in enumerate(items, start=1):
            print(x, y)
        answer2 = input('Which item do you want to change the supply of?: ')
        answer3 = input('What number do you want to set the supply to?')
        viewbrands[lamtechitems.get(answer2)] = answer3
    with open(brands.get(answer1), 'w') as file2:
        json.dump(viewbrands, file2, indent=2)
#

all inputs where 1

#

let me send my json files too

zenith crypt
#

lamtechitems prob has no key 1

chrome tangle
#

lamtechfile.json:{
"type c to type c": 3,
"type c to usb": 2
}

zenith crypt
#

if u want to get key from value invert the dict

chrome tangle
zenith crypt
chrome tangle
zenith crypt
chrome tangle
zenith crypt
#

if u want the nth key u can do
dict.keys()[n-1]

chrome tangle
#

not the lamtechitems dict

zenith crypt
chrome tangle
wanton hamlet
#

input returns a string.

#

but your lamtechitems keys are integers

chrome tangle
#

wait i didnt put int()?

wanton hamlet
#

so lamtechitems.get("1") (for example) returns None, which ends up being encoded as "null" when dumping (because only string keys are allowed in JSON)

chrome tangle
#

man

wanton hamlet
#
answer2 = input('Which item do you want to change the supply of?: ')
chrome tangle
#

now i understand

#

i was sure i wrote the int()

#

yet im mistaken

wanton hamlet
#

don't use .get unless you're sure you want and can handle a None output if the key isn't found
if a key must be found, use dict index syntax d[k] which will throw an error if not found

chrome tangle
#

i dont know shit

wanton hamlet
#

which is why I'm telling you...

chrome tangle
#

d[k] is dict[key]?

wanton hamlet
#

yes

chrome tangle
#

also i know i could do that

#

but its impractical for the user

#

to type out the whole name of the item

wanton hamlet
#

I'm not telling you to make the user input the full name. I'm telling you to not use .get as the means of accessing your dict unless you're sure your code is okay with handling Nones

#

my recommendation doesn't require the user to type the full name, I'm not sure where you got that idea

chrome tangle
#

oh okay

chrome tangle
#

my bad

wanton hamlet
#

the key is still the int.
there's no difference between dict[key] and dict.get(key) beyond the fact that the former will throw an error on a missing key, and the latter will just silently give you None

chrome tangle
#

oh

#

i think i understand now thx

#

i seriously need to restudy dicts

#

thank you for your help

zenith crypt
#

dict.get(key) is the same as dict[key] except get returns None and the other errors if the key is not present

chrome tangle
#

okay

#

thx for the help @zenith crypt @wanton hamlet

#

!close

earnest mortarBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.