Skip to content

class UDict[KT, VT, CDV]

class UDict(dictionary: AnyDict[KT, VT]) # (1)!
class UDict(dictionary: AnyDict[KT, VT], *, default: CDV)
class UDict(**kwargs: VT)
class UDict(*, default: CDV, **kwargs: VT)
  1. AnyDict[KT, VT] = LikeDict[KT, VT] | dict[KT, VT]. In UDict

    Note

    LikeDict[KT, VT] is type which has __getitem__, __setitem__, __delitem__ and get() methods. UDict is LikeDict.

    Read about AnyDict and LikeDict


UDict as generic

You can use UDict as Generic, because of it, there are 3 TypeVars: KT, VT, CDV.

KT and VT are key type and value type. In inbuilt dict there are KT and VT type vars. CDV is class default value.

In this documentation KT, VT and CDV will be used in methods.

Create UDict object. If default, when not existent keys is given in getting item, method will return default.

Example

d = UDict(hello=world, hi=python, default=10)

(property, settable) dictionary: dict[KT, VT]

UDict's dictionary.

Example

print(d.dictionary)
d.dictionary = {4: 'world'}

Tip

You can use UDict to set dictionary

Example

d.dictionary = UDict({1: 7})

(property, settable) keys: list[KT]

UDict's keys

Example

print(d.keys)
d.keys = [1, 2]

Tip

You can use tuples to set keys

Example

d.keys = 1, 2

(property, settable) values: list[VT]

UDict's values

Example

print(d.values)
d.values = [7, 2]

Tip

You can use tuples to set values

Example

d.values = 7, 2

(property, settable) items: list[tuple[KT, VT]]

UDict's items.

Example

print(d.items)
d.items = [(1, 7), (2, 2)]

Tip

You can use tuples to set items or you can use tuples or lists with lists

Example

d.items = (1, 7), (2, 2)
d.items = [1, 7], [2, 2]

(property, settable) default: CDV

UDict's default value

Example

print(d.default)
d.default = 'null'

reverse() -> UDict[KT, VT, CDV]

Reverses UDict and returns it. (1)

  1. How UDict is being reversing?

    Just is being reversing items
    u{'hello': 1, 'hi': 2} -> u{'hi': 2, 'hello': 1} (reversed)

Warning

reverse() edits UDict. If you don't want to reverse UDict use reversed() method instead.

Example

d.reverse()
print(d) # prints reversed UDict

reversed() -> UDict[KT, VT, CDV]

Returns reversed UDict

Example

print(d.reversed())

Get reversed UDict with inbuilt reversed() and ~ operator

You can get reversed UDict with inbuilt reversed() and with invert operator (~).

Example

print(~d)
print(reversed(d))
print(d.reversed() == reversed(d)) # True

Read more about reversed() and ~ support in UDict

sort() -> UDict[KT, VT, CDV]

Sorts UDict and returns it. (1)

  1. How UDict is being sorting?

    Just are being sorting items by keys.
    u{'b': 1, 'a': 2} -> u{'a': 2, 'b': 1} (sorted)

Warning

sort() edits UDict. If you don't want to sort UDict use sorted() method instead.

Example

print(d.sort())

sorted() -> UDict[KT, VT, CDV]

Returns sorted UDict

Example

print(d.sorted())

get()

def get(*, key: KT) -> VT | CDV
def get(*, key: KT, default: DV) -> VT | DV
def get(*, index: int) -> VT | CDV
def get(*, index: int, default: DV) -> VT | DV
def get(*, value: VT) -> KT | CDV
def get(*, value: VT, default: DV) -> KT | DV

Using more than 1 argument

If you use 0 or 2 or 3 of this arguments (key, index, value), method will raise ValueError

Arguments:

key: KT

UDict value's key to find.

Example

print(d.get(key='key')) # same that d['key']

index: int

UDict value's index to find

Warning

Indexes are starting from 1. Index of first element of UDict is 1.

index argument more than UDict length

If you use index argument make sure that index are less than UDict length. Otherwise get() will raise IndexError

Example

print(d.get(index=2)) # second value of UDict

value: VT

UDict key's value to find

Example

print(d.get(value=1)) # if d = UDict{'hello': 1}, this will be 'hello'

default: DV

Default value, if the result was not found. If not provided, then default is UDict.default property.

Example

d = UDict(hello=1, hi=2, default=-1)
print(d.get(key='hell')) # -1
print(d.get(key='hell', default=None)) # None

is_empty() -> bool

Returns True if the UDict is empty (len(UDict) == 0), otherwise returns False.

Example

    d = UDict(hello=1)
    d2 = UDict()
    print(d.is_empty()) # False
    print(d2.is_empty()) # True

Convert UDict to bool

You can convert UDict to bool or use UDict in if statement. If UDict.is_empty() == True then bool(UDict) is False and by contrast. Same in if because of if x is the equivalent of if bool(x)

Example

# d is from code above
print(bool(d)) # True
if d:
    print("d is True") # d is True

Magic methods

Currently, UDict supports all these magic methods:

__call__(func: Callable[[KT, VT], VT]) -> UDict[KT, VT, CDV]

Returns new UDict, but all values generated with func function. First argument: key, second: value.

Arguments:

func: (KT, VT) -> VT

First argument of function is key, second is value. Returns new value

Example

def f(k, v):
    return v * 2
d = d(f) # multiply all values by 2

__neg__() -> UDict[KT, int | float, CDV]

Negates all values (if they support the - operator) to their opposite numbers.

Example

d = UDict(hello=1, hi=-2)
print(-d) # u{'hello': -1, 'hi': 2}

__invert__() -> UDict[KT, VT, CDV]

The equivalent of reversed()

Example

print(~d)

__reversed__() -> UDict[KT, VT, CDV]

The equivalent of reversed()

Example

print(reversed(d))

__getitem__(key: KT | int | slice) -> UDict[KT, VT, DV] | VT

Returns the value for a single key, or a UDict for multiple keys provided with a slice.

Indexes starting at 1.

Arguments:

key: KT | int | slice

Value's key or index to get or values's indexes slice to get.

Example

print(d['hello'])
print(d[1:2])

Using indexes

You can also use indexes in __getitem__().

Failure

Keep in mind that indexes are using after the keys with the given value were not found.

Example

If you have 1 key, d[1] syntax will use 1 how key, not index. If you want to use index in all ways, use get() instead.

Example

d = UDict(hello=1, hi=9)
print(d[2]) # 9

__setitem__(key: KT | int | slice, value: VT | list[VT] | tuple[VT])

Sets the value or values for the given key or keys.

key: KT | int | slice

Value's key or keys to set. This argument is the same with key argument in __getitem__() method

value: VT | list[VT] | tuple[VT]

Value or values to set.

Example

d = UDict(hello=2, hi=1)
d[2] = 'hello'
print(d['hi']) # 'hello'
d[:] = 'hello', 'world'
print(d) # u{'hello': 'hello', 'hi': 'world'}

__delitem__(key: KT | int | slice)

Deletes items with the given key or keys.

key: KT | int | slice

Item's key or keys to delete. This argument is the same with key argument in __getitem__() method.

__len__() -> int

Returns the length of the UDict.

Example

d = UDict(hello=1, hi=2) print(len(d)) # 2

__iter__() -> Iterator[tuple[KT, VT]]

Iterate over the UDict. The equivalent of items.__iter__().

Example

for k, v in d:
    print(f"Key: {k}\nValue: {v}") # Prints all keys and its values.

__bool__() -> bool

Returns whether the UDict is not empty. The equivalent of not is_empty()

Example

print(bool(d))
if d:
    print("D is not empty!")

__contains__(item: tuple[KT, VT] | list[KT | VT] | KT) -> bool

Checks whether the item or key is in the UDict.

Arguments:

item: tuple[KT, VT] | list[KT | VT] | KT

Item or item's key.

Example

if ('key', 'value') in d: ...
if ['key', 'value'] in d: ...
if 'key' in d: ...

__repr__() -> str

Returns the string representation of the UDict. This allows the UDict to be used in print() and repr().

Example

d = UDict(hello=1)
print(d) # u{'hello': 1}
print(repr(d)) # Same

__hash__() -> int

Returns the hash for repr(UDict). The equivalent of repr(UDict).__hash__().

__cmp__(other: dict[KT, VT] | UDict[KT, VT, CDV]) -> int

Used by @cmp_generator, which generates comparison magic methods like ==, !=, >, >=, <, <= operators.

Comparing UDicts involves comparing their lengths, except for __eq__().

Example

d = UDict(hello=1)
d2 = UDict(hello=1, hi=2)
print(d != d2) # True
print(d < d2) # True
print(d > d2) # False

__eq__(other: dict[KT, VT] | UDict[KT, VT, CDV]) -> bool

Checks whether UDicts are the same. (Overrides generated by @cmp_generator magic method)

Example

d = UDict(hello=1)
d2 = UDict(hello=1, hi=2)
print(d == d2) # False
print(d == d) # True

Tip

You can use dict to compare with UDict. Method will automatically generate UDict from this dict

print(d == {'hello': 1}) # True

__add__(other: dict[KT, VT] | UDict[KT, VT, CDV]) -> UDict[KT, VT, CDV]

Adds the dictionary or UDict's dictionary to the UDict's dictionary. This method also has r and i versions (+=).

Example

print(d + {'hi': 2})
print({'hi': 2} + d)
d += {'hi': 2}

__sub__(other: dict[KT, VT] | UDict[KT, VT, CDV]) -> UDict[KT, VT, CDV]

Subtracts the dictionary or UDict's dictionary from the UDict's dictionary. This method also has r and i versions (-=).

Example

d = UDict(hello=1, hi=2)
print(d - {'hello': 1}) # u{'hi': 2}
d -= {'hello': 1}
print(d) # Same

__mul__(other: dict[KT, float | int] | UDict[KT, float | int, DV] | float | int) -> UDict[KT, SupportsMul, CDV]

Multiply all values by other, if other is int or float. Multiply values with keys equals to other keys by other values, if other is dict or UDict. This method also have r and i version (*=)

Warning

Make sure that your UDict's values supports multiply operator (*)

Example

d = UDict(hello=1, hi=2)
print(d * 2) # {'hello': 2, 'hi': 4}
print(d * {'hi': 3}) # {'hello': 1, 'hi': 6}

__truediv__(other: dict[KT, float | int] | UDict[KT, float | int, DV] | float | int) -> UDict[KT, SupportsTrueDiv, CDV]

Same that __mul__(), but with divide operator (/).

Warning

Make sure that your UDict's values supports divide operator (/)

Example

d = UDict(hello=1, hi=2)
print(d / 2) # {'hello': 0.5, 'hi': 1}
print(d / {'hi': 4}) # {'hello': 1, 'hi': 0.5}